remoting 入门总结(转载)

来源:互联网 发布:类似初页的软件 编辑:程序博客网 时间:2024/06/07 05:01

一 远程对象的定义
客户端在获取服务器端对象时,并不是获得实际的服务端对象,

而是获得它的引用。因此在Remoting中,对于远程对象有一些必

须的定义规范要遵循。
由于Remoting传递的对象是以引用的方式,因此所传递的远程对

象类必须继承MarshalByRefObject
如:
public class ServerObject:MarshalByRefObject
{
  
}

二 服务器端应分为三步:
1、注册通道
 要跨越应用程序域进行通信,必须实现通道
Remoting提供了IChannel接口,分别包含TcpChannel和HttpChannel两种类型的通道
以TcpChannel为例。
首先要在项目中添加引用“System.Runtime.Remoting”,然后using名字空间:System.Runtime.Remoting.Channel.Tcp。代码如下:
            TcpChannel channel = new TcpChannel(8080);
            ChannelServices.RegisterChannel(channel);
2、注册远程对象
注册了通道后,要能激活远程对象,必须在通道中注册该对象。根据激活模式的不同,注册对象的方法也不同。

(1) SingleTon模式

对于WellKnown对象,可以通过静态方法RemotingConfiguration.RegisterWellKnownServiceType()来实现:RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(ServerRemoteObject.ServerObject),
                "ServiceMessage",WellKnownObjectMode.SingleTon);

(2)SingleCall模式

注册对象的方法基本上和SingleTon模式相同,只需要将枚举参数WellKnownObjectMode改为SingleCall就可以了。RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(ServerRemoteObject.ServerObject),
                "ServiceMessage",WellKnownObjectMode.SingleCall);

(3)客户端激活模式

对于客户端激活模式,使用的方法又有不同,但区别不大,看了代码就一目了然。
RemotingConfiguration.ApplicationName = "ServiceMessage";
RemotingConfiguration.RegisterActivatedServiceType(
                typeof(ServerRemoteObject.ServerObject));

3、注销通道

如果要关闭Remoting的服务,则需要注销通道,也可以关闭对通道的监听。
   //获得当前已注册的通道;
            IChannel[] channels = ChannelServices.RegisteredChannels;//RegisterdChannel属性获得的是当前已注册的通道

            //关闭指定名为MyTcp的通道;
            foreach (IChannel eachChannel in channels)
            {
                if (eachChannel.ChannelName == "MyTcp")
                {
                    TcpChannel tcpChannel = (TcpChannel)eachChannel;

                    //关闭监听;
                    tcpChannel.StopListening(null);

                    //注销通道;
                    ChannelServices.UnregisterChannel(tcpChannel);
                }
            }