使用Remoting技术

来源:互联网 发布:中国烟草总公司 知乎 编辑:程序博客网 时间:2024/04/27 13:21

         在Wifi网络环境下,我们常用WebService作为服务程序构建分布式的应用程序系统,但是现在越来越多的应用在GPRS网络,因此WebService访问性能的问题渐渐体现出来.为了解决GPRS网络下快速构建分布式应用系统的问题,必须找到一种访问效率高于WebService,且开发效率高于直接采用Socket的方式.基于以上原因,我们尝试采用Remoting技术作为服务程序提供服务.
         Remoting技术实质上是Dll的远程调用技术,由于该技术支持HTTP,TCP和IPC方式,因此,直觉上感觉使用该技术传输XML,效率要高于WebService和Servlet方式,本文设计了一个简单的用于XML传送的Remoting,并与WebService做了测试,实验表明,Remoting采用Tcpip时运行效率远高于WebService.
         采用Remoting方式传输字符串时需要构建一个中间DLL,该DLL需要同时加载到服务器端和客户端,客户端通过实例化服务器端的DLL中的类对象,并调用其中的方法实现XML字符串的传递.
         程序实现如下:
1.公共DLL
namespace StringBridge
{
    public class StringBridge: System.MarshalByRefObject
    {
        protected string strXml = "";
        public StringBridge()
        {
            ......
        }
        //客户端调用,用于获取传送过来的字符串
        public void SetString(string strXml)
        {
            this.strXml = strXml;
     Console.Writeln(strXml); //测试输出
            return;

        }
    }
}
注:从System.MarshalByRefObject类继承出来的对象在运行时不会离开自己的程序域,事实上从该基类下派生的子类可以被客户端远程调用.
2.服务器端:
创建控制台应用程序,导入System.Runtime.Remoting命名空间,然后再导入StringBridge库.
 using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpServerChannel tcpServer = new TcpServerChannel(8086);
            ChannelServices.RegisterChannel(tcpServer, false);
            System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType(typeof(StringBridge.StringBridge), "Hi",
                WellKnownObjectMode.SingleCall); //告诉远程客户端,那个对象可以被调用.
            System.Console.WriteLine("Press return to exit");
            System.Console.ReadLine();
        }
    }
}
WellKnownObjectMode.SingleCall属性告诉服务程序每次有客户端登录时为客户端创建一个独立的实例.
注意:System.Runtime.Remoting命名空间要通过"引用"-"添加引用"-".Net"-"System.Runtime.Remoting"来引用.
3.客户端:
创建控制台应用程序,同样导入System.Runtime.Remoting命名空间,然后再导入StringBridge库.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            ChannelServices.RegisterChannel(new TcpClientChannel(), false);
            StringBridge.StringBridge obj = (StringBridge.StringBridge)Activator.GetObject(typeof(RemoteHello.Hello),"tcp://localhost:8086/Hi");

            obj.SetString("<MESSAGE><HEAD><ACTIONID>LOGIN</ACTIONID></HEAD></MESSAGE>"); //调用方法传送字符串          
            Console.ReadLine();
        }
    }
}

运行服务器端程序,然后在运行客户端程序,会看到客户端的XML发送到了服务器端.
建立实现相同功能的WebService,分别在WebService上和Remoting方式调用1000次该操作,共做10组操作,WIFI网络上平均运行时间分别8900ms和691ms,由此可见,后者比前者性能提高10倍,完全可以适应GPRS这种低速网络 

原创粉丝点击