- 1:新建一个MessageObject类库
- 代码如下:
- using System;
- using System.Collections.Generic;
- namespace MessageObject
- {
- //MarshalByRefObject 允许在支持远程处理的应用程序中跨应用程序域边界访问对象。
- public class RemoteObject : MarshalByRefObject
- {
- public static Queue<string> qMessage { get; set; } //使用消息队列储存消息
- public string SendMessage(string message)
- {
- if (qMessage == null)
- {
- qMessage = new Queue<string>();
- }
- qMessage.Enqueue(message);
- return message;
- }
- }
- }
- 2:新建一个控制台程序,名称:IPCServer,是IPC的服务端
- using System;
- using System.Runtime.Remoting.Channels.Ipc;
- using System.Runtime.Remoting.Channels;
- using System.Runtime.Remoting;
- using MessageObject;
- using System.Threading;
- using System.Collections.Generic;
- namespace IPCServer
- {
- /// <summary>
- /// IPC Server
- /// </summary>
- class Program
- {
- static void Main(string[] args)
- {
- StartServer();
- Thread t = new Thread(new ThreadStart(ReceviceMessage)); //使用线程获取消息
- t.Start();
- }
- private static void StartServer()
- {
- IpcServerChannel channel = new IpcServerChannel("ServerChannel");
- ChannelServices.RegisterChannel(channel, false);
- RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall);
- Console.WriteLine("message server running...");
- }
- private static void ReceviceMessage()
- {
- while (true)
- {
- Queue<string> qMessage = RemoteObject.qMessage;
- if (qMessage != null)
- {
- if (qMessage.Count > 0)
- {
- string message = qMessage.Dequeue();
- Console.WriteLine("recevice message is:" + message);
- }
- }
- Thread.Sleep(1000); //每一秒获取一次
- }
- }
- }
- }
- 3:新建一个控制台程序,名称:IPCClient,IPC客户端
- 代码如下:
- using System;
- using MessageObject;
- using System.Runtime.Remoting.Channels.Ipc;
- using System.Runtime.Remoting.Channels;
- namespace IPCClient
- {
- class Program
- {
- static void Main(string[] args)
- {
- RemoteObject objRemoteObject = ConnectServer();
- Send(objRemoteObject);
- }
- private static void Send(RemoteObject objRemoteObject)
- {
- while (true)
- {
- Console.WriteLine("please input message...");
- string message = Console.ReadLine();
- try
- {
- objRemoteObject.SendMessage(message);
- Console.WriteLine("send success");
- }
- catch (System.Runtime.Remoting.RemotingException)
- {
- Console.WriteLine("can not connect message server");
- }
- }
- }
- private static RemoteObject ConnectServer()
- {
- IpcClientChannel channel = new IpcClientChannel();
- ChannelServices.RegisterChannel(channel, false);
- RemoteObject objRemoteObject = (RemoteObject)Activator.GetObject(typeof(RemoteObject), "ipc://ServerChannel/RemoteObject");
- return objRemoteObject;
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2304201512409.html
来源: http://www.codesnippet.cn/detail/2304201512409.html