三.几个重要的概念:
四.开发Remoting三步走:
开发.NET Remoting分三步走,在这里以一个简单的例子来说明。
1.创建远程对象:
继承System.MarshalByRefObject
1using System;
2using System.Collections;
3using System.Text;
4
5namespace SimpleRemoting
6{
7 public class HelloServer : MarshalByRefObject
8 {
9 public HelloServer()
10 {
11 /**////输出信息,服务器激活
12 Console.WriteLine("服务器激活……");
13 }
14 public String HelloMethod(String name)
15 {
16 Console.WriteLine(
17 "服务器端 : {0}", name);
18 return "这里是:" + name;
19 }
20 }
21}
2.创建宿主应用程序:
注册通道
注册服务器激活的远程对象
运行宿主程序
1using System;
2using System.Net;
3using System.Runtime.Remoting;
4using System.Runtime.Remoting.Channels;
5using System.Runtime.Remoting.Channels.Tcp;
6using System.Runtime.Remoting.Channels.Http;
7
8namespace SimpleRemoting
9{
10
11 public class Server
12 {
13 public static int Main(string [] args)
14 {
15
16 /**////创建Tcp通道
17 TcpChannel chan1 = new TcpChannel(8085);
18
19 /**////创建Http通道
20 HttpChannel chan2 = new HttpChannel(8086);
21
22 /**////注册通道
23 ChannelServices.RegisterChannel(chan1);
24 ChannelServices.RegisterChannel(chan2);
25
26 RemotingConfiguration.RegisterWellKnownServiceType
27 (
28 typeof(HelloServer),
29 "SayHello",
30 WellKnownObjectMode.Singleton
31 );
32
33
34 System.Console.WriteLine("按任意键退出!");
35 /**////下面这行不能少
36 System.Console.ReadLine();
37 return 0;
38 }
39
40 }
41}
3.建立客户端程序:
注册通道
根据URL得到对象代理
使用代理调用远程对象
1using System;
2using System.Runtime.Remoting;
3using System.Runtime.Remoting.Channels;
4using System.Runtime.Remoting.Channels.Tcp;
5using System.Runtime.Remoting.Channels.Http;
6using System.IO;
7
8namespace SimpleRemoting
9{
10 public class Client
11 {
12 public static void Main(string[] args)
13 {
14 /**////使用TCP通道得到远程对象
15 TcpChannel chan1 = new TcpChannel();
16 ChannelServices.RegisterChannel(chan1);
17
18 HelloServer obj1 = (HelloServer)Activator.GetObject(
19 typeof(SimpleRemoting.HelloServer),
20 "tcp://localhost:8085/SayHello");
21
22 if (obj1 == null)
23 {
24 System.Console.WriteLine(
25 "连接TCP服务器失败");
26 }
27
28 /**////使用HTTP通道得到远程对象
29 HttpChannel chan2 = new HttpChannel();
30 ChannelServices.RegisterChannel(chan2);
31
32 HelloServer obj2 = (HelloServer)Activator.GetObject(
33 typeof(SimpleRemoting.HelloServer),
34 "http://localhost:8086/SayHello");
35
36 if (obj2 == null)
37 {
38 System.Console.WriteLine(
39 "连接HTTP服务器失败");
40 }
41
42 /**////输出信息
43 Console.WriteLine(
44 "ClientTCP HelloMethod {0}",
45 obj1.HelloMethod("Caveman1"));
46 Console.WriteLine(
47 "ClientHTTP HelloMethod {0}",
48 obj2.HelloMethod("Caveman2"));
49 Console.ReadLine();
50 }
51 }
52}
53
结束语:
初识用.NET Remoting来开发分布式应用就到这里了,有时间我会就.NET Remoting技术写成系列文章。包括基于租约的生存期,编组,异步远程调用等等。