技术开发 频道

Castle 整合.NET Remoting


【IT168技术文档】

  今天研究了一下Castle的Remoting Facility.记录如下:

  微软以前使用COM/DCOM的技术来处理分布式系统架构,通过Client端的Proxy代理程序来呼叫远程Server机器上的对象。.NET Framework则使用.NET Remoting或Web Services技术来实作分布式处理的工作概念;在这里针对.NET Remoting的设计架构做一个初步的简介和Castle整合示例。

  .NET Framework提供了多种的机制来支持Remoting,如:

  .利用Channel来负责信息的发送与接收。
  .利用Formatter来负责在信息要通过channel发送出去之前,先将信息做适当的加密,或于信息在通过Channel接收进来之后,先将信息做相对的解密工作。
  .利用Proxy来呼叫远程的对象执行所要的功能呼叫。

  其关系如下图所示:

  Channel 和 Formatter
  在远程对象被使用之前,必须先在Server端注册好信息发送的信道(Channel),这些Channel可通过.NET Remotin configuration file或 ChannelServices对象类别的RegisterChannel方法来注册。

  在Channel的使用上,.NET Framework支持HTTP、TCP及SMTP等通道。若使用HTTP Channel ,则使用SOAP协议来收送信息,所有的信息会被发送到SOAP Formatter中,被序列化(serialized)成XML的格式,而SOAP所需的headers也会被加入。至于使用TCP Channel者,则使用TCP协议来将信息发送到Binary Formatter中,以Binary Stream的方式来将信息发送到URI目的地。(URI : Universal Resource Identifier,类似大家所熟悉的URL)。

  Activation and Proxy
  Server-Side Activation
  Server端在Client端要获取Remoting对象时必需在Server端能自动启动Remoting对象,可使用RemotingConfiguration对象类别的RegisterWellKnownServiceType方法来完成这项工作。

  Client-Side Activation
  Client端要使用远程对象之前,可使用New 或Activator 对象类别所提供的CreateInstance或GetObject方法来启动对象并传回Proxy,以便Client端可通过Proxy来执行叫用远程对象的方法。 

  范例
  以下分三个步骤来介绍

  1. 建立Remoting对象

  2. 在Server上初始Remoting物件

  3. Client端使用Remoting对象

  步骤1:建立Remoting对象
  建立一个MathServer对象类别,提供Sum方法,可给予一连串的整数由Sum方法代为计算总和。程序代码如下,并说明于后:
using System; namespace RemoteSample.Components { /// <summary> /// Class1 的摘要说明。 /// </summary> public interface IRemoteMath { int Sum(params int[] a); int CallCounter { get; } } }
using System; using RemoteSample.Components; namespace RemoteSample.Components { /// <summary> /// RemoteMath 的摘要说明。 /// </summary> public class RemoteMath: MarshalByRefObject,IRemoteMath { private int callCounter = 0; public RemoteMath() { } #region 接口IRemoteMath的成员实现 /// <summary> /// 求和计算 /// </summary> /// <param name="a"></param> /// <returns></returns> public int Sum(params int[] a) { int sum = 0; for (int i = 0; i <= a.Length - 1; i++) { sum += a[i]; } callCounter += 1; return sum; } public int CallCounter { get { return this.callCounter; } } #endregion } }

0
相关文章