創建一個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();//在能夠看到結果前不讓窗口關閉 }