关于Remoting的一个简单的调用列子

关于Remoting,在.net framework  2.0开始的,到3.5已经集成到WCF中,可一些老的项目还是用到了,现在写一个简单的例子帮助你去改一些比较老的项目。

 

Remoting就是客户端,通过服务器端去访问方法,符合分布式开发。下面将例子。

1、首先定义类库,也就是我们到时候要调用的方法。

 

/// <summary>
    
/// 允许在支持远程处理的应用程序中跨应用程序域边界的访问对象
    
/// 必须继承MarshalByRefObject
    
/// </summary>
    public class MYRemotingMethod:MarshalByRefObject
    {
        public int AddMethod(int i, int j)
        {
            return i * j;
        }
    }
View Code

 

2、定义服务端,服务端定义为一个应用程序,代码如下,总共有三种调用方式,代码里面有详细的介绍

//创建tcp remoting通道
            TcpChannel tcpCh = new TcpChannel(1001);
            //创建 httpremoting通道
            HttpChannel httpCh = new HttpChannel(1002);
            //IPC通道  IPC只适合同系统内的通信,不需要设置端口号和主机名
            IpcChannel ipcCh = new IpcChannel("ipcServer");
            //注册通道
            ChannelServices.RegisterChannel(tcpCh);
            ChannelServices.RegisterChannel(httpCh);
            ChannelServices.RegisterChannel(ipcCh);
            //打印出 tcp  http  ipc通道的名称和优先级
            Console.WriteLine("TCP通道的名称是" + tcpCh.ChannelName);
            Console.WriteLine("TCP通道的优先级" + tcpCh.ChannelPriority);

            Console.WriteLine("---------------");
            Console.WriteLine("TCP通道的名称是" + httpCh.ChannelName);
            Console.WriteLine("TCP通道的优先级" + httpCh.ChannelPriority);
            Console.WriteLine("---------------");
            Console.WriteLine("TCP通道的名称是" + ipcCh.ChannelName);
            Console.WriteLine("TCP通道的优先级" + ipcCh.ChannelPriority);
            Console.WriteLine("---------------");

            //注册方法到remoting 库中,
           
//配置远程通信的框架
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingObject.MYRemotingMethod), "abc", WellKnownObjectMode.Singleton);
            Console.WriteLine("Press any key to exit!");
            System.Console.ReadLine();
View Code

3、客户端调用的方法如下:

 

try
            {
                string urlTcp = "tcp://localhost:1001/abc";
                RemotingObject.MYRemotingMethod proxyObjectTcp = (RemotingObject.MYRemotingMethod)Activator.GetObject(typeof(RemotingObject.MYRemotingMethod), urlTcp);


                //通过代理访问对象的方法,输出结果
                Console.WriteLine("This call object by TcpChannel = {0}", proxyObjectTcp.AddMethod(100200));
                Console.ReadLine();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
View Code

总结:有人会问,在客户端调用的时候,你可以直接实例类库的方法,为什么还要通过代理去访问类库的方法呢?我现在的理解是,这是分布式开发的思想,我还没有捅破那层窗户纸,以后会咋补上自己的理解,如果你有独到的见解,可以到群里跟我讨论QQ:115180614

 

 

posted @ 2014-07-13 14:12  hg000  阅读(263)  评论(0编辑  收藏  举报