何为.Net Remoting

借助基维百科给它的定义如下:

NET Remoting 是微软 .NET Framework 中的一种网络通讯技术,与 XML Web Service 不同的是,它可以使用 SOAP 以外的协定来通讯,而在伺服端和用户端之间所操作的方法近乎相同,用户端可以不必考虑使用的协定,即可存取伺服端所开放的物件。这个技术与是由Distributed COM所发展而来的,与DCOM最大的不同是,DCOM有限制使用 TCP Port,但.NET Remoting 可以选择使用 TCP 或 HTTP 的方式通讯,而资料可以利用 SOAP 或二进制传输方式在网络上流动,二进制的传输效能是 SOAP 所不能比的,但 SOAP 却可以得到和 Web Service 相互沟通的能力,因此 .NET Remoting 的设计弹性较大。

.NET Remoting 技术目前已整合到 Windows Communication Foundation 中。

原理

.NET Remoting 使用了 ChannelSerialization 机制来串接两台机器间的物件,Channel 是负责处理网络通讯的部份,而 Serialization 则是处理物件与串流资料的处理工作。

  • Channel 支援了 IPC(行程间通讯)、TCP 与 HTTP 通讯协定[1]
  • Serialization 支援二进制(binary)或 XML(SOAP)通讯协定的资料串流[2]

当伺服端设定好使用的通道以及协定后,用户端必须要跟随伺服端的设定,并且依伺服端决定的活化模型来启动,而程式设计的方法和一般呼叫元件般简单。

public static void Main()
{
   RemotingConfiguration.Configure("Client.exe.config"); // configure Remoting configuration.
   RemotableType remoteObject = new RemotableType(); // create remoting object.
   Console.WriteLine(remoteObject.SayHello()); // call remoting object's method.
}

组态设定

.NET Remoting 的设计理念,就是为了要简化网络上的物件通讯,而且要让开发人员不必太过于在通讯的底层伤脑筋,因此在网络通讯协定上做了许多的包装,并且允许在 Configuration File(app.config)中直接设定,或是由 .NET Remoting 的 Configuration API 来设定即可,故组态设定的选项复杂度较高,设计较复杂的 .NET Remoting 应用程式在组态的设定上往往会相当复杂。

以下为设定 .NET Remoting 用户端的范例设定:

<configuration>
   <system.runtime.remoting>
      <application>
         <client>
            <wellknown 
               type="RemotableType, RemotableType"
               url="http://localhost:8989/RemotableType.rem"
            />
         </client>
      </application>
   </system.runtime.remoting>
</configuration>

活化模型

活化(Activation)是指用户端启动伺服端元件的方式,.NET Remoting 中支援了两种方式[3]

  • Single-Call:在每一次用户端呼叫时都生成一个执行个体。
  • Single-ton:在第一次呼叫时就生成执行个体,之后每一次呼叫都使用相同的执行个体。

物件传递

在 .NET Remoting 中,不论是传值或传址,每一个物件都必须要继承 System.MarshalByRefObject 类别,才可以利用 .NET Remoting 来传输[4]

以下程式码为服务端的 Remoting 元件:

// RemotableType.cs
using System;
public class RemotableType : MarshalByRefObject // Remoting 物件必須繼承自 System.MarshalByRefObject 類別。
{
    public string SayHello()
    {
        Console.WriteLine("RemotableType.SayHello() was called!");
        return "Hello, world";
    }
}
原文地址:https://www.cnblogs.com/lori/p/2362339.html