[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. 创建远程对象代理,完成调用。

后面的章节将就这些内容去做点研究。 
posted on 2007-06-05 09:30  编程山人  阅读(455)  评论(0编辑  收藏  举报