.Net对于远程调用提供了两种方法:Remoting和WebService。WebService是一种标准,可以通用。对于Remoting不是标准应用,有平台限制。
1.在Remoting中,远程对象是一个重要的概念。服务端通过将它注册到特定的信道中,客户端通过服务端公布的服务端注册的远程对象的URI,通过代理来使用它。在这种架构下服务端与客户端要实现相互之间的通讯一般是使用事件的方式进行。
2.Remoting的模型可以大致分为三块:客户端、远程对象、服务端。
3.远程对象一般需要继承MarshalByRefObject类,而继承自MarshalByRefObject的对象是不会离开它的应用程序域的。并且为了安全,一般我们都是通过将远程对象实现的接口提供给客户端,而不是远程对象。同时,远程对象应该重写基类的InitializeLifetimeService方法,目的是为了远程对象永不过期。
4.Remoting 的通道主要有两种:tcp 和 http。在.net 中,system.runtime.remoting.channel中定义了 ichannel 接口。ichannel 接口包括了 tcpchannel 通道类型和 http 通道类型。它们分别对应 remoting 通道的这两种类型。
服务端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Tcp;
namespace Server
{
class Program
{
static void Main(string[] args)
{
//注册服务通道
TcpServerChannel tcpSerChanne=new TcpServerChannel(6666);
System.Runtime.Remoting.Channels.ChannelServices.RegisterChannel(tcpSerChanne);
//注册远程对象
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteObject.RemoteObject), "RemoteObject", WellKnownObjectMode.SingleCall);
//RemoteObject.RemoteObject remoteObject = new RemoteObject.RemoteObject();
//RemotingServices.Marshal(remoteObject, "RemoteObject", typeof(RemoteObject.RemoteObject));
Console.ReadLine();
}
}
}
远程对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemoteObject
{
/// <summary>
/// 远程对象类
/// </summary>
public class RemoteObject:MarshalByRefObject
{
/// <summary>
/// 构造函数
/// </summary>
public RemoteObject()
{
Console.WriteLine("Remoting测试:");
}
/// <summary>
/// 返回一个1到100之间的随机数
/// </summary>
/// <returns></returns>
public int GetRandom()
{
Random random = new Random();
return random.Next(1, 100);
}
/// <summary>
/// 重写基类的InitializeLifetimeService方法,目的是保证远程对象永不过期
/// </summary>
/// <returns></returns>
public override object InitializeLifetimeService()
{
return null;
}
}
}
客户端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace Client
{
public class Program
{
static void Main(string[] args)
{
TcpClientChannel tcpChannel = new TcpClientChannel();
ChannelServices.RegisterChannel(tcpChannel);
RemoteObject.RemoteObject remoteObject = Activator.GetObject(typeof(RemoteObject.RemoteObject), "tcp://localhost:6666/RemoteObject", null) as RemoteObject.RemoteObject;
Console.WriteLine("返回的随机数为:" + remoteObject.GetRandom());
Console.ReadLine();
}
}
}
效果图:
1.服务端:
2.客户端: