Remoting三种信道
IPC,HTTP,TCP
访问速度:IPC>TCP>HTTP
HTTP信道:在跨越防火墙上有优势
TCP信道:通常在局域网内通信
IPC信道:同一机器的进程间通信,不占用网络资源
TcpChannel
默认使用二进制序列化消息对象,理好的传输性能,适用于局域网中
HttpChannel
默认使用Soap序列化消息对象,更好的互操作性,可穿越防火墙
对象的激活方式
服务端激活
SingleCall: 一次客户端调用一个实例
SingleTon: 所有客户端共用实例
SingleTon实现方式1
- client获取对象方式1
var remoteType = new WellKnownClientTypeEntry(typeof(RemoteObject),"ipc://localhost:9090/RemoteObject.rem");
RemotingConfiguration.RegisterWellKnownClientType(remoteType);
var obj = new RemoteObject();
- client获取对象方式2
var obj1 = (RemoteObject) Activator.GetObject(typeof(RemoteObject),"ipc://localhost:9090/RemoteObject.rem");
- server端注册服务对象
var serverChannel = new IpcChannel("localhost:9090");
// Register the server channel.
ChannelServices.RegisterChannel(serverChannel);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "RemoteObject.rem", WellKnownObjectMode.Singleton);
- SingleTon实现方式2,服务端提供特定的对象作为服务对象。
TcpChannel channel = new TcpChannel(9001);
ChannelServices.RegisterChannel(channel, false);
var ob = new RemoteObject();
ObjRef obj = RemotingServices.Marshal(ob, "ServiceMessage");
ob.PrintName();
客户端激活
一个客户端一个实例
server
TcpChannel channel = new TcpChannel(9001);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.ApplicationName = "ServerObject";
RemotingConfiguration.RegisterActivatedServiceType(typeof(RemoteObject));
client
TcpChannel channel = new TcpChannel();
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterActivatedClientType(typeof(RemoteObject), "tcp://localhost:9001/ServerObject");
var so = new RemoteObject();
so.PrintName();
远程对象的定义
继承自MarshalByRefObject, 传递引用
多通道定义
需要以通道名区分不同的通道,当然,端口号也需要不同。
IDictionary pro1 = new Hashtable();
pro1["name"] = "tcp9090";
pro1["port"] = 9090;
IChannel ch1 = new TcpChannel(pro1,
new BinaryClientFormatterSinkProvider(),
new BinaryServerFormatterSinkProvider());
ChannelServices.RegisterChannel(ch1, false);
IDictionary pro2 = new Hashtable();
pro2["name"] = "tcp8080";
pro2["port"] = 8080;
IChannel ch2 = new TcpChannel(pro2,
new BinaryClientFormatterSinkProvider(),
new BinaryServerFormatterSinkProvider());
ChannelServices.RegisterChannel(ch2, false);
通道注销
如果需要关闭Remoting服务,需要注销通道,或关闭通道监听(通道存在,但无法接收请求)。
//获得当前已注册的通道;
IChannel[] channels = ChannelServices.RegisteredChannels;
//关闭指定名为MyTcp的通道;
foreach (IChannel eachChannel in channels)
{
if (eachChannel.ChannelName == "MyTcp")
{
TcpChannel tcpChannel = (TcpChannel)eachChannel;
//关闭监听;
tcpChannel.StopListening(null);
//注销通道;
ChannelServices.UnregisterChannel(tcpChannel);
}
}