分散式處理機制,適用 .NET 平台間 程式通訊,不支援離線訊息。可視為 DCOM 的 .NET 升級版,極佳融合於 .NET 生態。核心價值:跨越 AppDomain 邊界 進行物件互動 (OS 進程隔離保護機制下的受控穿透)。

| 通道 | 協定 | 宿主 | 安全性 | 參數 |
|---|---|---|---|---|
| HttpChannel | HTTP | ASP.NET | 可用 HTTP 加密 | 主機名 + 埠號 |
| TcpChannel | TCP Socket | Windows Service / EXE | 無內建安全 | 主機名 + 埠號 |
| IpcChannel | Named Pipe | 同機器進程間 | 無內建安全 | 管道名 (無需主機/埠) |
| 自訂通道 | UDP/SMTP/MSMQ 等 | 任意 | 自行實作 | 自訂 |
客戶端取得的不是實體物件,而是透明代理,經真實代理 → 通道 → 伺服端物件。
透明代理 (客戶端) → Invoke → 真實代理 → 訊息沉澱器 → 通道 → 伺服端。
namespace RemoteObject
{
public class MyRemoteObject : MarshalByRefObject
{
public int AddForTcpTest(int a, int b) => a + b;
public int MinusForHttpTest(int a, int b) => a - b;
public int MultipleForIpcTest(int a, int b) => a * b;
}
}
static void Main()
{
// 註冊三種通道
ChannelServices.RegisterChannel(new TcpChannel(10001));
ChannelServices.RegisterChannel(new HttpChannel(10002));
ChannelServices.RegisterChannel(new IpcChannel("FrankTestIpc"));
// 註冊 WellKnown 服務 (Singleton)
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteObject.MyRemoteObject),
"RemoteObject.MyRemoteObject",
WellKnownObjectMode.Singleton);
Console.WriteLine("Server ready. Press any key to exit.");
Console.ReadLine();
}
App.config
<appSettings>
<add key="ServiceURLTcp" value="tcp://localhost:10001/RemoteObject.MyRemoteObject" />
<add key="ServiceURLHttp" value="https://localhost:10002/RemoteObject.MyRemoteObject" />
<add key="ServiceURLIpc" value="ipc://FrankTestIpc/RemoteObject.MyRemoteObject" />
</appSettings>
呼叫代碼
static void Main()
{
try
{
var tcpProxy = (RemoteObject.MyRemoteObject)Activator.GetObject(
typeof(RemoteObject.MyRemoteObject),
ConfigurationSettings.AppSettings["ServiceURLTcp"]);
Console.WriteLine("TCP: 100+200 = {0}", tcpProxy.AddForTcpTest(100, 200));
var httpProxy = (RemoteObject.MyRemoteObject)Activator.GetObject(
typeof(RemoteObject.MyRemoteObject),
ConfigurationSettings.AppSettings["ServiceURLHttp"]);
Console.WriteLine("HTTP: 100-200 = {0}", httpProxy.MinusForHttpTest(100, 200));
var ipcProxy = (RemoteObject.MyRemoteObject)Activator.GetObject(
typeof(RemoteObject.MyRemoteObject),
ConfigurationSettings.AppSettings["ServiceURLIpc"]);
Console.WriteLine("IPC: 100*200 = {0}", ipcProxy.MultipleForIpcTest(100, 200));
}
catch (Exception e) { throw e; }
Console.ReadLine();
}
伺服器:三通道註冊成功。
客戶端:三通道分別呼叫遠端方法運算成功。


非同步呼叫、安全性、Lease 生命週期管理、自訂沉澱器。下一篇將介紹 Enterprise Services 與 COM+ 事務機制。
完整代碼下載:Remoting.rar