Jaasdsa

导航

 

 IPC可以实现本地进程之间通信。这种用法不是太常见,常见的替代方案是使用wcf,remoting,web service,socket(tcp/pipe/...)等其他分布式部署方案来替代进程之间的通信。虽然不常见但也避免不了一些场景会使用该方案。

  应用包含:

1)使用IPC技术实现多client与一个sever通信(不过是本机,感觉意义不大,但如果想实现本机上运行确实是一个不错的方案);

2)使用IPC技术实现订阅者和生产者分离时,一个server接收并消费消息,客户端是生产消息的。

 View Code

  使用技巧:

1)使用之间必须定义好一个进程之间通信的对象(该对象继承了MarshalByRefObject ,允许在支持远程处理的应用程序中跨应用程序域边界访问对象);

复制代码
 1     public class MyProcessSendObject : MarshalByRefObject
 2     {
 3         private string taskInfo = string.Empty;
 4 
 5         public void Add(string taskInfo)
 6         {
 7             Console.WriteLine("Add:{0}", taskInfo);
 8             this.taskInfo = taskInfo;
 9         }
10 
11         public string GetTask()
12         {
13             Console.WriteLine("GetTask:{0}", taskInfo);
14             return taskInfo;
15         }
16 
17     }
复制代码

2)服务端是发布了一个IPC服务,供客户端段来绑定使用;

复制代码
 1         //I PC(inter process communication)的功能可以实现同一台机器上的不同进程间通信。
 2         static void Main(string[] args)
 3         {
 4             Console.WriteLine("I'm server......");
 5             //Instantiate our server channel.
 6             IpcChannel serverchannel = new IpcChannel("testchannel");
 7             //Register the server channel.
 8             ChannelServices.RegisterChannel(serverchannel, false);
 9             //Register this service type.
10             RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyProcessSendObject), "myObj", WellKnownObjectMode.Singleton);

13 Console.WriteLine("press Enter to exit"); 14 Console.ReadLine(); 15 Console.WriteLine("server stopped"); 16 }
复制代码

3)客户端使用时需要绑定服务端发布的地址,之后获取发布的对象(暂时可以这么理解:数据的传递和同步是通过对象序列化、反序列化),在客户端操作该对象时实际上是操作了服务端的对象。

复制代码
 1         static void Main(string[] args)
 2         {
 3             Console.WriteLine("I'm client......");
 4             IpcChannel tcc = new IpcChannel();
 5             ChannelServices.RegisterChannel(tcc, false);
 6 
 7             MyProcessSendObject myObj = (MyProcessSendObject)Activator.GetObject(typeof(MyProcessSendObject), "ipc://testchannel/myObj");
 8             
 9             Console.WriteLine("client send myvalue start");
10             myObj.Add("Task 1");
11             myObj.GetTask();
12             myObj.Add("Task 2");
13             myObj.GetTask();
14             Console.WriteLine("client send myvalue complete");
15             Console.ReadLine();
16         }
复制代码

工程结构:

测试:

posted on 2018-03-13 14:23  Jaasdsa  阅读(254)  评论(0编辑  收藏  举报