.NET分布式Remoting学习,不错的Remoting教程
首先一个remoting的程序需要服务端和客服端的两个程序组成。我写了一个计算加法的例子来说明remoting的一些简单知识。
在服务端和客户端里写代码时,需要添加几个引用和命名空间:
1 using System.Runtime.Remoting;
2 using System.Runtime.Remoting.Channels;
3 using System.Runtime.Remoting.Channels.Tcp;
4 using System.Runtime.Remoting.Channels.Http;
这几个命名空间在开发remoting项目时可以说是必须要引入的。
下面就涉及到通道了。通道有两种类型:tcp通道和http通道。下面来看看如何注册通道:
1 TcpChannel tcpchannel = new TcpChannel(8080);
2 HttpChannel httpchannel = new HttpChannel(8081);
3
4 ChannelServices.RegisterChannel(tcpchannel);
5 ChannelServices.RegisterChannel(httpchannel);
这个通道的注册是比较简单的,下面来看看如何注册远程对象:
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Add), "add", WellKnownObjectMode.Singleton);
注册远程对象有两种方式:Singleton和SingleCall。Singleton是单对象实例化,SingleCall是多对象实例化
以上都是服务端的情况,下面看看客户端的情况:先注册通道:
Code
1 TcpChannel tcpchannel = new TcpChannel();
2 ChannelServices.RegisterChannel(tcpchannel);
3
4 Add addmethod = (Add)Activator.GetObject(typeof(Add), "tcp://localhost:8080/add");
5
6 if (addmethod == null)
7 Console.WriteLine(
8 "Could not locate TCP server");
9
10 HttpChannel httpchannel = new HttpChannel();
11 ChannelServices.RegisterChannel(httpchannel);
12
13 Add addmethod1 = (Add)Activator.GetObject(typeof(Add), "http://localhost:8081/add");
然后就是调用add方法,完成调用。
在我们开发的时候,有些代码可以写到配置文件中,方便以后维护