创建一个C# Library,并将其命名为RemoteObject。这将创建一个我们的.NET Remote客户端和服务器端用来通讯的“共享命令集”。 public class RemoteObject : System.MarshalByRefObject { public RemoteObject() { System.Console.WriteLine("New Referance Added!"); }
public int sum(int a, int b) { return a + b; } } 名字空间是对象所需要的。请记住,如果得到System.Runtime.Remoting.Channels.Tcp名字空间不存在的信息,请检查是否象上面的代码那样添加了对System.Runtime.Remoting.dll的引用。
2)将服务端上的对象 Type 注册为已知类型。 RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall); 这行代码设置了服务中的一些参数和把欲使用的对象名字与远程对象进行绑定,第一个参数是绑定的对象,第二个参数是TCP或HTTP信道中远程对象名字的字符串,第三个参数让容器知道,当有对对象的请求传来时,应该如何处理对象。尽管WellKnownObjectMode.SingleCall对所有的调用者使用一个对象的实例,但它为每个客户生成这个对象的一个实例。如果用WellKnownObjectMode.SingleCall则每个传入的消息由同一个对象实例提供服务。
完整的对象代码如下所示: using System; using System.Runtime; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using RemoteSample; namespace RemoteSampleServer { public class RemoteServer { public static void Main(String[] args) { TcpServerChannel channel = new TcpServerChannel(8808); ChannelServices.RegisterChannel(channel); RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall); System.Console.WriteLine("Press Any Key"); System.Console.ReadLine(); } } } 保存文件,命名为RemoteServer.cs 用命令行csc /r:System.Runtime.Remoting.dll /r:RemoteObject.dll RemoteServer.cs 编译这一程序生成的RemoteServer.EXE文件。
using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using RemoteSample; namespace RemoteSampleClient { public class RemoteClient { public static void Main(string[] args) { ChannelServices.RegisterChannel(new TcpClientChannel()); RemoteObject remoteobj = (RemoteObject)Activator.GetObject( typeof(RemoteObject), "tcp://localhost:8808/RemoteObject"); Console.WriteLine("1 + 2 = " + remoteobj.sum(1,2).ToString()); Console.ReadLine();//在能够看到结果前不让窗口关闭 }