.Net Remoting 小程序

    技术2025-05-15  51

    CS 程序中有时需要进程间通信,比较方便的一种便是 .net remoting 技术。当遇到无法跨越不同机器调用时(即代码运行需要特定的运行环境,而本台机器没有,别的机器有)可以采用这种方式,我认为比较好的例子便是 sharepoint 中 文档转换服务的应用,那个服务便是采用了 remoting 技术把 LoadBalancer 和 Launcher 发布成两个不同的 windows 服务,然后很方便的提供用户调用。下面有一个简单的例子,共分三部分,即 Client, Server ,和 RemoteClass,其中 Client 和 Server 都必须引用该 RemoteClass,Server 将该 RemoteClass 发布成Client 可认可的类型,RemoteClass 必须继承自System.MarshalByRefObject 类。

     

    本文采用的是 WellKnownObjectMode.Singleton 方式发布的服务,该方式能够记录状态,如想每次调用都是一个新的实例请采用

     WellKnownObjectMode.SingleCall 模式

    1、RemoteClass

    public class RemoteObjClass : System.MarshalByRefObject { Person p; int i = 0; public RemoteObjClass() { if (p == null) { p = new Person(); } } public String DisplayMessage() { return "HelloWorld" + i++; } public int Multi(int a, int b) { return i++; //return a * b; } public void SetName(String name) { p.Name = name; } public String GetName() { return p.Name; } [Serializable] public class Person { public Person() { } private string name; private string sex; private int age; public string Name { get { return name; } set { name = value; } } public string Sex { get { return sex; } set { sex = value; } } public int Age { get { return age; } set { age = value; } } } }

    2、Server端 ,当然也可以发布成 windows 服务,本文以控制台为例,如果有防火墙,则最好采用 HttpChannel 方式。

    static void Main(string[] args) { try { TcpChannel chnl = new TcpChannel(8888); ChannelServices.RegisterChannel(chnl, true); RemotingConfiguration.RegisterWellKnownServiceType(Type.GetType("RemoteObject.RemoteObjClass,RemoteObject"), "Test", WellKnownObjectMode.Singleton); Console.WriteLine("Server is running..."); Console.ReadLine(); } catch (Exception exc) { Console.WriteLine(exc.ToString()); Console.ReadLine(); } }

    3、Client 端,如果采用 HttpChannel ,Client 也要相应的修改成 HttpChannel 方式调用

    static void Main(string[] args) { try { TcpClientChannel chnl = new TcpClientChannel(); ChannelServices.RegisterChannel(chnl, true); RemoteObjClass obj = (RemoteObjClass) Activator.GetObject(Type.GetType("RemoteObject.RemoteObjClass,RemoteObject"), "tcp://localhost:8888/Test"); Console.WriteLine(obj.Multi(3, 6)); obj.SetName("MrZhao"); string name = obj.GetName(); Console.WriteLine(name); Console.ReadLine(); } catch (Exception exc) { Console.WriteLine(exc.ToString()); Console.ReadLine(); } }

     

    最新回复(0)