遠程方法調用(RMI)發展至今,歷經 DCE/RPC、CORBA、DCOM、MTS/COM+、Java RMI/EJB、Web Services/SOAP 等框架。本文聚焦 .NET Remoting,剖析其原理、實作細節,並與微軟早期 COM/DCOM 技術進行對比。
Microsoft .NET Remoting 提供跨應用程式域的物件互動框架。相較於 Web Service 僅支援簡單的跨平台/跨語言呼叫,.NET Remoting 如同 ASP 之於 CGI,帶來質的飛躍:
| 要素 | 角色 |
|---|---|
| Proxy(代理) | 客戶端偽裝成遠端物件,轉發呼叫給 Remoting 框架。 |
| Message(訊息) | 封裝方法呼叫所需的參數、屬性等資料。 |
| Message Sink / Channel Sink(訊息槽/通道槽) | 攔截並自訂訊息處理管線,提供擴充點。 |
| Formatter(格式化器) | 將 Message 序列化為網路傳輸格式(SOAP、Binary)。 |
| Transport Channel(傳輸通道) | 負責將序列化訊息傳送至遠端處理序(HTTP、TCP)。 |
TransparentProxy,其介面與遠端物件完全一致。IMessage 轉交 RealProxy。RealProxy 負責跨應用程式域/處理序轉發訊息。// 客戶端啟動遠端物件典型代碼
HttpChannel channel = new HttpChannel();
ChannelServices.RegisterChannel(channel);
SomeClass obj = (SomeClass)Activator.GetObject(
typeof(SomeClass),
"https://localhost:1234/SomeSAO.soap");
一次 setValue(42) 呼叫經過 HTTP Channel 後的 SOAP 封包:
POST /MyRemoteObject.soap HTTP/1.1
SOAPAction: "https://schemas.microsoft.com/clr/nsassem/General.BaseRemoteObject/General#setValue"
Content-Type: text/xml; charset="utf-8"
<SOAP-ENV:Envelope ...>
<SOAP-ENV:Body>
<i2:setValue id="ref-1">
<newval>42</newval>
</i2:setValue>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
.NET Remoting 以 Formatter 取代 COM 複雜的 Marshaling/Unmarshaling:
SoapFormatter(XML)與 BinaryFormatter(二進位)。IMessageSink 前處理鏈 → SyncProcessMessage → Formatter 序列化。SoapClientFormatterSink 呼叫 SerializeMessage,最終由 CoreChannel.SerializeSoapMessage 完成。實作 IClientChannelSink 即可在訊息管線中插入壓縮邏輯,展現框架極高擴充性:
public class CompressionClientSink : BaseChannelSinkWithProperties, IClientChannelSink
{
private IClientChannelSink _nextSink;
public CompressionClientSink(IClientChannelSink next) { _nextSink = next; }
public IClientChannelSink NextChannelSink => _nextSink;
public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg,
ITransportHeaders headers, Stream stream)
{
// TODO: 壓縮前處理
sinkStack.Push(this, null);
_nextSink.AsyncProcessRequest(sinkStack, msg, headers, stream);
}
// ... 其他介面成員省略
}
「若需跨異構系統互操作,請選 Web Service(SOAP/XML/HTTP);若雙端皆為 CLR 托管元件,.NET Remoting 可能是更佳選擇。」
.NET Remoting 以簡潔的 Proxy/Message/Sink 架構、強大的型別系統與高度可擴展的管線設計,重新定義了 .NET 平台上的分散式物件呼叫。雖然 WCF 後來統一了通訊模型,但理解 Remoting 核心機制仍有助於深入掌握 .NET 分散式運算本質。