創(chuàng)建一個(gè)C# Library,并將其命名為RemoteObject。這將創(chuàng)建一個(gè)我們的.NET Remote客戶端和服務(wù)器端用來(lái)通訊的“共享命令集”。 public class RemoteObject : System.MarshalByRefObject { public RemoteObject() { System.Console.WriteLine("New Referance Added!"); }
public int sum(int a, int b) { return a + b; } } 名字空間是對(duì)象所需要的。請(qǐng)記住,如果得到System.Runtime.Remoting.Channels.Tcp名字空間不存在的信息,請(qǐng)檢查是否象上面的代碼那樣添加了對(duì)System.Runtime.Remoting.dll的引用。
2)將服務(wù)端上的對(duì)象 Type 注冊(cè)為已知類型。 RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall); 這行代碼設(shè)置了服務(wù)中的一些參數(shù)和把欲使用的對(duì)象名字與遠(yuǎn)程對(duì)象進(jìn)行綁定,第一個(gè)參數(shù)是綁定的對(duì)象,第二個(gè)參數(shù)是TCP或HTTP信道中遠(yuǎn)程對(duì)象名字的字符串,第三個(gè)參數(shù)讓容器知道,當(dāng)有對(duì)對(duì)象的請(qǐng)求傳來(lái)時(shí),應(yīng)該如何處理對(duì)象。盡管WellKnownObjectMode.SingleCall對(duì)所有的調(diào)用者使用一個(gè)對(duì)象的實(shí)例,但它為每個(gè)客戶生成這個(gè)對(duì)象的一個(gè)實(shí)例。如果用WellKnownObjectMode.SingleCall則每個(gè)傳入的消息由同一個(gè)對(duì)象實(shí)例提供服務(wù)。
完整的對(duì)象代碼如下所示: 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();//在能夠看到結(jié)果前不讓窗口關(guān)閉 }