什么是Remoting,简而言之,我们可以将其看作是一种分布式处理方式。从微软的产品角度来看,可以说Remoting就是DCOM的一种升级,它改善了很多功能,并极好的融合到.Net平台下。Microsoft .NET Remoting 提供了一种允许对象通过应用程序域与另一对象进行交互的框架。这也正是我们使用Remoting的原因。为什么呢?在Windows操作系统中,是将应用程序分离为单独的进程。这个进程形成了应用程序代码和数据周围的一道边界。如果不采用进程间通信(RPC)机制,则在一个进程中执行的代码就不能访问另一进程。这是一种操作系统对应用程序的保护机制。然而在某些情况下,我们需要跨过应用程序域,与另外的应用程序域进行通信,即穿越边界。
.Net对于远程调用提供了两种方法:Remoting和WebService,那么比起WebService,Remoting更适合于中小型局域网应用,而不适用于企业级的应用。
Remoting具有以下特点:
优点:
1、Tcp通道的Remoting速度非常快
2、虽然是远程的,但是非常接近于本地调用对象
3、可以做到保持对象的状态
4、没有应用程序限制,可以是控制台,winform,iis,windows服务承载远程对象
缺点:
1、不是标准的应用,因此有平台限制
2、脱离iis的话需要有自己的安全机制
下面给出一个Remoting的Demo:
调用对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RemoteObjects
{
public class RemoteObject : System.MarshalByRefObject
{
public RemoteObject()
{
Console.WriteLine("New Referance Added!");
}
public int GetRdm(int a, int b)
{
Random rdm = new Random();
try
{
return rdm.Next(a, b);
}
catch
{
return 0;
}
}
}
}
Server:
using System;
using System.Runtime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteObjects;
namespace RemoteServer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Remoting server start...");
Console.Write("Regist Channel...");
TcpServerChannel channel = new TcpServerChannel(8201);
ChannelServices.RegisterChannel(channel, true);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall);
Console.WriteLine("OK");
Console.ReadKey(true);
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
Client:
using System;
using System.Runtime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteObjects;
namespace RemoteClient
{
class Program
{
static void Main(string[] args)
{
ChannelServices.RegisterChannel(new TcpClientChannel(), true);
RemoteObject remoteobj = (RemoteObject)Activator.GetObject(typeof(RemoteObject), "tcp://localhost:8201/RemoteObject");
Console.WriteLine("[1, 100) => " + remoteobj.GetRdm(1, 100).ToString());
Console.ReadLine();
Console.ReadKey(true);
}
}
}