涉及到的类:
客户端:
1.System.Runtime.Remoting.Channel.Tcp.TcpClientChannel类:为远程调用实现使用 TCP 协议传输消息的客户端信道。
信道跨越远程处理边界(例如,计算机或应用程序域)传输消息。TcpClientChannel 类使用 TCP 协议传输消息。
.NET Framework 远程处理基础结构使用信道传输远程调用。当客户端调用远程对象时,该调用即被序列化为一个消息,该消息通过客户端信道发送并通过服务器信道接收。然后将其反序列化并进行处理。所有返回值都通过服务器信道传输,并通过客户端信道接收。
2.System.Runtime.Remoting.Channel.ChannelService类:提供帮助进行远程处理信道注册、解析和 URL 发现的静态方法。无法继承此类。
3.System.Activator类:包含特定的方法,用以在本地或从远程创建对象类型,或获取对现有远程对象的引用。无法继承此类。
服务器端:
1.System.Runtime.Remoting.Channel.ChannelService类:提供帮助进行远程处理信道注册、解析和 URL 发现的静态方法。无法继承此类。
2.System.Runtime.Remoting.Channel.Tcp.TcpServerChannel类:为远程调用实现使用 TCP 协议传输消息的服务器信道。
3.System.Runtime.Remoting.RemotingConfiguration类:提供多种配置远程处理结构的静态方法。
4.System.Runtime.Remoting.WellKnownObjectMode枚举:定义如何激活已知对象。
成员名称 | 说明 | |
---|---|---|
SingleCall | 每个传入的消息由新的对象实例提供服务。 | |
Singleton | 每个传入的消息由同一个对象实例提供服务。 |
1.设计自己的远程对象类:RemoteObject.
2.服务器端把远程对象用RemotingConfiguration.RegisterWellKnownServiceType方法注册为WellKnownServiceTypeEntry实例
3.服务器端注册TcpServerChannel到ChannelService中
4.客户端注册新的TcpClientChannel到ChannelService中。
5.客户端用Activator类从远程服务器的URL获取远程对象。
6.客户端使用远程对象。
远程对象代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RemoteSampleLib
{
public class RemoteObject : MarshalByRefObject
{
public RemoteObject()
{
Console.WriteLine("New RemoteObject Added!");
}
public int Add(int a, int b)
{
return a + b;
}
}
}
服务器端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteSampleLib;
using System.Runtime.Remoting.Channels;
namespace RemoteServer
{
class RemoteServer
{
static void Main(string[] args)
{
TcpServerChannel channel = new TcpServerChannel(6666);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteSampleLib.RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall);
System.Console.WriteLine("Press Any Key");
System.Console.ReadLine();
}
}
}
客户端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteSampleLib;
namespace RemoteClient
{
class RemoteClient
{
static void Main(string[] args)
{
ChannelServices.RegisterChannel(new TcpClientChannel());
RemoteObject remoteobj = (RemoteObject)Activator.GetObject(typeof(RemoteObject), "tcp://localhost:6666/RemoteObject");
Console.WriteLine("1+2=" + remoteobj.Add(1, 2).ToString());
Console.ReadLine();
}
}
}
注意远程对象要实现MarshalByRef类来允许远程对象被跨程序边界访问。