开发平台为Visual Studio 2005,.NET framework版本为2.0
1、 建立空白解决方案
2、 添加两个新工程项目Console Application:Server和Client
3、 添加一个Class Library:RemoteObject
4、 三个项目的源代码Server.cs、Client.cs、RemoteObject.cs分别附后
5、 在Server和Client项目的引用中添加两个程序集:
System.Runtime.Remoting程序集(.net组件)和RemoteObject程序集(工程组件)
6、 生成两个工程之后,双击打开Server程序,再打开Client,可以看到两者通信。
7、 程序逻辑很简单:
Client根据约定好的对象地址(URI)“ipc://ServerChannel/RemoteObject”去服务器上访问RemoteObject对象。Server在收到访问对象的消息之后,实例化一个RemoteObject对象。当Client得到生成的RemoteObject对象句柄后,调用其Greeting方法,这个调用被传递到Server端执行(因为RemoteObject对象实际上是在Server上),然后返回Greeting方法的结果给Client。
8、 简言之,即完成了Client进程访问Server进程的一个对象,并调用此对象的方法的任务。
9、 源代码:
RemoteObject.cs
using System; public class RemoteObject : MarshalByRefObject { public RemoteObject() { Console.WriteLine("Constructor called"); } public string Greeting(string name) { Console.WriteLine("Greeting called"); return "Hello," + name; } } |
Server.cs
using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; public class Server { public static void Main(string[] args) { //Instantiate our server channel. IpcServerChannel channel = new IpcServerChannel("ServerChannel"); //Register the server channel. ChannelServices.RegisterChannel(channel, false); //Register this service type. RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall); Console.WriteLine("press return to exit"); Console.ReadLine(); } } |
Client.cs
using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; public class Client { public static void Main(string[] args) { //Create an IPC client channel. IpcClientChannel channel = new IpcClientChannel(); //Register the channel with ChannelServices. ChannelServices.RegisterChannel(channel, false); RemoteObject obj = (RemoteObject)Activator.GetObject(typeof(RemoteObject), "ipc://ServerChannel/RemoteObject"); if (obj == null) { Console.WriteLine("could not locate server"); return; } for (int i = 1; i < 5; i++) { Console.WriteLine(obj.Greeting("mmpire")); } } } |
Server输出:
press return to exit
Constructor called
Greeting called
Constructor called
Greeting called
Constructor called
Greeting called
Constructor called
Greeting called
Client输出:
Hello,mmpire
Hello,mmpire
Hello,mmpire
Hello,
5689



被折叠的 条评论
为什么被折叠?



