在此系列随笔中,注重代码实例,对原理的深入研究不想提及太多
远程对象的两个含义:
一,操作远程对象;
1,对象运行在远程,客户端向其发送消息.
2,继承之MarshalByRefObject
二,传递远程对象;
1,将远程对象拿到本地,或者将本地对象发送过去;
2,对副本进行操作,对远程对象没有影响;
3,添加[Serializable]属性或实现ISerizable接口.
对于远程对象的激活,有两种方式,一是服务器端激活,一是客户端激活
远程对象是使用通道发送和接收消息的,首先,服务器端选择一个通道来监听请求(request),而客户端选择通道来和服务器通讯,.Net Remoting框架中内置了TCP与HTTP通道,我们也可以开发我们自己的通道类型.
一般的Remoting开发分三个步骤:
1,创建远程对象;
2,创建"宿主(host)"应用程序,以接收客户端请求;
3,创建一个客户端对远程对象进行调用.
下面,说一下一个最简单的Remoting Demo
第一步.创建远程对象,在VS.NET中新建一个类库,新建一个类HelloServer,跟普通类没有不同,必须有不带参构造器且继承于类MarshalByRefObject或实现接口ISerizable(同添加[Serizable]属性)代码如下:

 1.Net Remoting 入门(2)using System;
 2.Net Remoting 入门(2)using System.Collections.Generic;
 3.Net Remoting 入门(2)using System.Text;
 4.Net Remoting 入门(2)
 5.Net Remoting 入门(2)namespace General
 6

第二步,创建宿主应用程序
1,注册通道(内置TCP,HTTP)
2,注册服务器激活的远程对象(WellKnow)
这里要说一下WellKnownObjectMode中的Singleton与Singlecall,个人理解:
Singleton 服务器端只产生单例,任何请求共用,保存状态,
Singlecall 客户端每一次请求,服务器端都会产生一个新的实例,没有状态
在VS.NET中新建一个控制台应用程序,新建类Server,代码:
 1.Net Remoting 入门(2)using System;
 2.Net Remoting 入门(2)using System.Collections.Generic;
 3.Net Remoting 入门(2)using System.Text;
 4.Net Remoting 入门(2)using System.Runtime.Remoting.Channels;
 5.Net Remoting 入门(2)using System.Runtime.Remoting;
 6.Net Remoting 入门(2)using System.Runtime.Remoting.Channels.Tcp;
 7.Net Remoting 入门(2)using System.Runtime.Remoting.Channels.Http;
 8.Net Remoting 入门(2)using General;
 9.Net Remoting 入门(2)namespace Server
10

第三步,创建客户端程序
1,注册通道(TCP,HTTP or Other);
2,根据URL得到对象代理;
3,使用代理调用远程对象
在VS.NET中新建一个控制台应用程序,新建类Client,代码:
 1.Net Remoting 入门(2)using System;
 2.Net Remoting 入门(2)using System.Collections.Generic;
 3.Net Remoting 入门(2)using System.Text;
 4.Net Remoting 入门(2)using System.Runtime.Remoting.Channels.Tcp;
 5.Net Remoting 入门(2)using System.Runtime.Remoting.Channels.Http;
 6.Net Remoting 入门(2)using System.Runtime.Remoting.Channels;
 7.Net Remoting 入门(2)using General;
 8.Net Remoting 入门(2)namespace Client
 9

先启动Server,再启动Client,测试Demo
此Demo代码下载:
/Files/mshwu/RemotingDemo1.rar

相关文章:

  • 2022-02-16
  • 2022-03-09
  • 2021-05-19
  • 2021-11-02
  • 2021-06-24
  • 2021-06-04
  • 2021-09-26
猜你喜欢
  • 2022-03-01
  • 2022-12-23
  • 2022-02-07
  • 2022-01-29
  • 2022-01-21
  • 2021-11-07
  • 2021-12-28
相关资源
相似解决方案