[Remoting] 一:.NET Remoting

有太多的原因让我忽略了 Remoting,不过现在用它来开始 SOA 和 WCF 的旅途还是不错的选择。.NET Remoting 封装了分布式开发的消息编码和通讯方式,让我们用非常简单的方式既可完成不同模式的分布系统开发,同时其可配置、可扩展的特性也让我们拥有极大的灵活性。当然,我更看好其升级版本 —— WCF。

要了解 Remoting 的基本信息和介绍,还是看 MSDN 比较好。先写一个简单的 Example 来体验一下,为了方便,我直接在一个工程里面创建不同的应用程序域来模拟分布模式。

using System;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.CompilerServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Messaging;

namespace Learn.Library.Remoting
{
  public class RemotingTest
  {
    /// <summary>
    /// 远程类型
    /// </summary>
    public class Data : MarshalByRefObject
    {
      private int i;

      public int I
      {
        get { return i; }
        set { i = value; }
      }

      public void Where()
      {
        Console.WriteLine("{0} in {1}", this.GetType().Name, AppDomain.CurrentDomain.FriendlyName);
      }
    }

    /// <summary>
    /// 服务器端代码
    /// </summary>
    static void Server()
    {
      // 创建新的应用程序域,以便模拟分布系统。
      AppDomain server = AppDomain.CreateDomain("server");
      server.DoCallBack(delegate
      {
        // 创建并注册信道
        TcpServerChannel channel = new TcpServerChannel(801);
        ChannelServices.RegisterChannel(channel, false);

        // 注册远程对象激活模式
        RemotingConfiguration.RegisterWellKnownServiceType(typeof(Data), "data",
          WellKnownObjectMode.Singleton);
      });
    }

    /// <summary>
    /// 客户端代码
    /// </summary>
    static void Client()
    {
      // 创建并注册信道
      TcpClientChannel channel = new TcpClientChannel();
      ChannelServices.RegisterChannel(channel, false);

      // 创建远程对象并调用其方法
      Data data = (Data)Activator.GetObject(typeof(Data), "tcp://localhost:801/data");
      data.Where();

      // 判断是否是代理
      Console.WriteLine(RemotingServices.IsTransparentProxy(data));
    }

    static void Main()
    {
      Server();
      Client();
    }
  }
}


在 Remoting 中,核心内容包括 "远程对象" 和 "信道",前者是我们要使用的内容,后者则提供了分布环境的封装。使用 Remoting 一般包括如下步骤:

1. 创建可远程处理的类型。
2. 注册信道。
3. 注册远程类型(以及其激活方式)。
4. 创建远程对象代理,完成调用。

后面的章节将就这些内容去做点研究。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值