我在一个项目中定义了一个类Msg
public class Msg : MarshalByRefObject
{
public int TestInt{ get; set; }
public string TestStr { get; set; }
public int TestMothedResult { get; private set; }
public void TestMothed()
{
TestMothedResult++;
}
}
然后在另外的一个Winform项目中作为Servo,
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RemotingTest
{
public partial class Servo : Form
{
RemotingObject.Msg Msg { get; set; } = new RemotingObject.Msg();
public Servo()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// ------------------------------------------------------------
BinaryServerFormatterSinkProvider serverProv =
new BinaryServerFormatterSinkProvider();
serverProv.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary propBag = new Hashtable();
// -----------------------------------------
propBag["port"] = 6666;
propBag["typeFilterLevel"] = TypeFilterLevel.Full;
propBag["name"] = "RemotingObject.Msg";
TcpChannel channel = new TcpChannel(propBag, null, serverProv);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObject.Msg), "RemotingObject.Msg", WellKnownObjectMode.Singleton);
}
void timer1_Tick(object sender, EventArgs e)
{
nud_Read.Value = Msg.TestMothedResult;
}
void button1_Click(object sender, EventArgs e)
{
Msg.TestMothed();
}
}
}
又在另外的一个Winform项目中作为Client,
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RemotingClient
{
public partial class Client : Form
{
RemotingObject.Msg Msg { get; set; }
public Client()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string Url = "tcp://localhost:6666/RemotingObject.Msg";
object temp = Activator.GetObject(typeof(RemotingObject.Msg), Url);
if (temp is RemotingObject.Msg)
{
Msg = temp as RemotingObject.Msg;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (Msg != null)
{
txt_Read.Text = Msg.TestStr;
nud_Read.Value = Msg.TestMothedResult;
}
}
private void button1_Click(object sender, EventArgs e)
{
if (Msg != null)
{
Msg.TestMothed();
}
}
}
}
无论是服务端还是客户端,我的界面都是这个样子:
我的目的,是在无论服务端还是客户端进行修改时,对方也能被修改(简单说就是类似同一个实例);可事实上是 程序运行不报错,断点跟踪也是正常设置与监控,但就是各管各的!