IPCChannel是NET Framework 里面新增的它使用 Windows 进程间通信 (IPC) 系统在同一计算机上的应用程序域之间传输消息在同一计算机上的应用程序域之间进行通信时IPC 信道比 TCP 或 HTTP 信道要快得多但是IPC只在本机应用之间通信所以在客户端和服务端在同一台机器时我们可以通过注册IPCChannel来提高Remoting的性能但如果客户端和服务端不在同一台机器时我们不能注册IPCChannel
下面让我们来看看如何使用IPCChannel
首先我们定义一个RemotingObject类
using System;// 远程对象public class RemoteObject : MarshalByRefObject{ private int callCount = ; public int GetCount() { ConsoleWriteLine(GetCount has been called); callCount++; return(callCount); }}
接下来我们编写服务端代码
using System;using SystemRuntimeRemotingChannelsIpc;using SystemSecurityPermissions;public class Server{[SecurityPermission(SecurityActionDemand)] public static void Main(string[] args) { // 创建一个IPC信道 IpcChannel serverChannel = new IpcChannel(TestChannel); // 注册这个IPC信道 SystemRuntimeRemotingChannelsChannelServices
RegisterChannel(serverChannel); // 打印这个信道的名称 ConsoleWriteLine(The name of the channel is {} serverChannelChannelName); // 打印这个信道的优先级 ConsoleWriteLine(The priority of the channel is {} serverChannelChannelPriority); // 打印这个信道的URI数组 SystemRuntimeRemotingChannelsChannelDataStore channelData =
(SystemRuntimeRemotingChannelsChannelDataStore) serverChannelChannelData; foreach (string uri in channelDataChannelUris) { ConsoleWriteLine(The channel URI is {} uri); } // 向信道暴露一个远程对象 SystemRuntimeRemotingRemotingConfigurationRegisterWellKnownService
Type(typeof(RemoteObject) RemoteObjectrem SystemRuntimeRemoting
WellKnownObjectModeSingleton); ConsoleWriteLine(Press ENTER to exit the server); ConsoleReadLine(); ConsoleWriteLine(The server is exiting); } }
客户端代码
using System;using SystemRuntimeRemotingChannelsIpc;using SystemSecurityPermissions;public class Client{[SecurityPermission(SecurityActionDemand)] public static void Main(string[] args) { // 创建一个IPC信道 IpcChannel channel = new IpcChannel(); // 注册这个信道 SystemRuntimeRemotingChannelsChannelServicesRegisterChannel
(channel); // 注册一个远程对象的客户端代理 SystemRuntimeRemotingWellKnownClientTypeEntry remoteType
= new SystemRuntimeRemotingWellKnownClientTypeEntry(typeof(RemoteObject)
ipc://TestChannel/RemoteObjectrem); SystemRuntimeRemotingRemotingConfigurationRegisterWellKnownClient
Type(remoteType); RemoteObject service = new RemoteObject(); ConsoleWriteLine(The client is invoking the remote object); ConsoleWriteLine(The remote object has been called {} times serviceGetCount()); } }
主要代码就算完成了但还有一个问题那就是如果服务端和客户端在不同的Windows帐户运行的时候会有验证权限的问题对于这个问题我们只要把服务端的信道注册代码改一下就好了
Hashtable ht = new Hashtable();ht[portName] = TestChannel;ht[name] = ipc;ht[authorizedGroup] = Everyone; serverChannel= new IpcChannel(ht null provider);