Skip to content

.NET Remoting

.NET远程处理层(Remoting)是一个比较古老的概念吧,Framework 1.0就存在。远程处理是两个对象跨应用程序域进行通信的行为,两个对象可以在同一计算机,也可以不在;在同一计算机也可以存在于不同的进程和应用程序域(AppDomain)

优点:

  • 便于我们进行分布式开发
  • TCP通道的Remoting速度非常快
  • 虽然是远程的,但是非常接近于本地调用对象
  • 可以做到保持对象的状态
  • 没有应用程序限制,可以是控制台,Windows Form,IIS,Windows服务承载远程对象

缺点:

  • 属于非标准的应用,因此有平台限制
  • 脱离IIS的话需要有自己的安全机制

公共DLL中定义的消息类:(定义在公共DLL中,供客户端和服务器端引用,避免循环编译依赖)

using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace RemotingLibrary { public class RemoteMessageObject : MarshalByRefObject { private int m_MessageCount = 0;

    public RemoteMessageObject()
    {
        Console.WriteLine("Constructing RemoteMessageObject.");
    }

    public void DisplayMessage(string message)
    {
        m_MessageCount++;
        Console.WriteLine("[{0}]Message is: {1}", m_MessageCount.ToString(), message);
    }

    public string ReturnMessage()
    {
        return "Remoting Server Message Count: " + m_MessageCount.ToString();
    }
}

}

服务器端:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Remoting.Channels.Http; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting; using RemotingLibrary;

namespace CLRRemoting { class Program { static void Main(string[] args) { Console.WriteLine("========= Server Started =======");

        HttpChannel c = new HttpChannel(30001);
        ChannelServices.RegisterChannel(c, false);

        RemotingConfiguration.RegisterWellKnownServiceType(
            typeof(RemoteMessageObject),
            "RemoteMessageObject.soap",
            WellKnownObjectMode.Singleton);
        Console.ReadLine();
    }
}

}

客户端:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Remoting.Channels.Http; using System.Runtime.Remoting.Channels; using RemotingLibrary;

namespace RemotingClient { class Program { static void Main(string[] args) { Console.WriteLine("========= Client Started ======="); HttpChannel c = new HttpChannel(); ChannelServices.RegisterChannel(c, true);

        object remoteObject = Activator.GetObject(
            typeof(RemoteMessageObject),
            "http://itsserver2:30001/RemoteMessageObject.soap");
        RemoteMessageObject sample = remoteObject as RemoteMessageObject;
        if (sample != null)
        {
            for (int i = 0; i < 10; i++)
            {
                sample.DisplayMessage("Client Message" + i.ToString());
                Console.WriteLine(sample.ReturnMessage());
            }
            Console.ReadLine();
        }
    }
}

}

代码简单,就不介绍了。我把Server部署在局域网远程的服务器上。 远程对象被定义为WKO,只有在第一次访问的时候才构造。5分钟没有访问对象时,远程对象会被垃圾收集器收集,再次访问的时候,编号和构造函数都重新开始。

我的想法,我最近想写一个比较大的东西,最近在仔细研究WCF,估计Remoting将是我的并行程序的核心。