1.什么是Remoting
- 简而言之,我们可以将其看作是一种分布式处理方式。从微软的产品角度来看,可以说 Remoting 就是 DCOM的一种升级,它改善了很多功能,并极好的融合到.NET平台下。Microsoft? .NET Remoting 提供了一种允许对象通过应用程序域与另一对象进行交互的框架。这也正是我们使用 Remoting 的原因。
- 在 Remoting 中是通过通道(channel)来实现两个应用程序域之间对象的通信的。 首先,客户端通过Remoting,访问通道以获得服务端对象,再通过代理解析为客户端对象。这就提供一种可能性,即以服务的方式来发布服务器对象。远程对象代码可以运行在服务器上(如服务器激活的对象和客户端激活的对象),然后客户端再通过 Remoting 连接服务器,获得该服务对象并通过序列化在客户端运行。
- 在 Remoting 中,对于要传递的对象,设计者除了需要了解通道的类型和端口号之外,无需再了解数据包的格式。但必须注意的是,客户端在获取服务器端对象时,并不是获得实际的服务端对象,而是获得它的引用。这既保证了客户端和服务器端有关对象的松散耦合,同时也优化了通信的性能。
2.代码示例
类库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemoteObject
{
public class MyObject:MarshalByRefObject
{
public MyObject()
{
}
public void Add(int a, int b)
{
Console.WriteLine("========="+a+b);
}
}
}
客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RemoteObject;
using System.Configuration;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
namespace RemoteClient
{
class MyClient
{
static void Main(string[] args)
{
//声明TcpClientChannel类型的字段channels
TcpClientChannel channelc;
//声明MyObject类型的字段MyObject
MyObject remoteObject;
//创建TcpClientChannel对象,引用为channelc
channelc = new TcpClientChannel();
//将channels注册到信道服务
ChannelServices.RegisterChannel(channelc, false);
//创建远程对象
remoteObject = (MyObject)Activator.GetObject(typeof(MyObject), "tcp://127.0.0.1:3000/MyUri");
//调用服务的方法
remoteObject.Add(5, 6);
Console.WriteLine("调用成功");
Console.Read();
}
}
}
服务端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting.Channels;
using RemoteObject;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting;
namespace RemoteServer
{
class MyServer
{
static void Main(string[] args)
{
//声明TcpServerChannel类型的静态字段channels
TcpServerChannel channels;
//创建新的TcpServerChannel对象,端口号为3000,引用为channels
channels = new TcpServerChannel(3000);
//将channels注册到信道服务
ChannelServices.RegisterChannel(channels, false);
//创建知名服务类型的对象,传递远程对象的类型,对象URI和激活对象的枚举成员
RemotingConfiguration.RegisterWellKnownServiceType(typeof(MyObject), "MyUri", WellKnownObjectMode.Singleton);
//信息提示,当用户输入字符,则结束程序
Console.WriteLine("======服务器端已启动======");
Console.Read();
}
}
}