熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

讓.NET Remoting更快些-IPCChannel

2022-06-13   來源: .NET編程 

  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);


From:http://tw.wingwit.com/Article/program/net/201311/13151.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.