31、运行效果如下,示例可已在https://download.csdn.net/download/xingchengaiwei/89574208 下载。
2、项目结构,如下图 。
3、 RemoteObject中RemoteObject.cs类代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemoteObject
{
public class RemoteObject: MarshalByRefObject
{
private int _Count = 0;
public int Count()
{
_Count++;
return _Count;
}
public int Add(int add)
{
_Count += add;
return _Count;
}
}
}
4、ConsoleAppServer中Program.cs类代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
namespace ConsoleAppServer
{
class Program
{
static void Main(string[] args)
{
IpcChannel serverchannel = new IpcChannel("Serverchannel");
ChannelServices.RegisterChannel(serverchannel,false);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject.RemoteObject), "RemoteObject",WellKnownObjectMode.Singleton);
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
Console.WriteLine("Server Stopped");
}
}
}
5、ConsoleAppClient中Program.cs类代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
namespace ConsoleAppClient
{
class Program
{
static void Main(string[] args)
{
//创建IPC客户端信道。
IpcClientChannel channel = new IpcClientChannel();
//注册服务信道
ChannelServices.RegisterChannel(channel,false);
RemoteObject.RemoteObject obj =
(RemoteObject.RemoteObject)Activator.GetObject(typeof(RemoteObject.RemoteObject),
"ipc://Serverchannel/RemoteObject");
RemoteObject.RemoteObject remoteObject = new RemoteObject.RemoteObject();
//Console.WriteLine("{0} {1}", remoteObject.Count(), remoteObject.Add(20));
Console.WriteLine("{0} {1}", obj.Count(), obj.Add(20));
Console.ReadLine();
}
}
}
6、先运行ConsoleAppServer,在运行ConsoleAppClient,注意IPC一般用于本机间的进程通讯,如果要做不同主机间的进程通讯,我推荐使用Socket去完成。