分布式体系架构--Well-Know对象的激活(服务器激活)

来源:互联网 发布:淘宝怎么加心 编辑:程序博客网 时间:2024/06/06 19:31

注意:在使用本例前,首先要手动添加引用System.Runtime.Remoting.dll

1.新建一个接口类的程序集(dll),用于服务器端与客户端的引用(传送对象后识别对象的类型)

namespace remotinginterfaces
{
    public interface IAdder
    {
        double Add(double d1, double d2);
    }
}

2.建立服务器端,并引用上面的接口程序集,服务器端代码如下:

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using remotinginterfaces;

namespace remotingserver
{
    public class Adder:MarshalByRefObject,IAdder
    {

        public Adder()
        {
            //提示使用了构造方法
            Console.WriteLine("已经调用类的默认来构造方法,新建一个Adder类的对象实例");
        }
        #region IAdder 成员

        public double Add(double d1, double d2)
        {
            //提示进行垃圾收集的次数
            System.Console.Title = string.Format("{0}:{1}:{2}",
                GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2));
            //提示进行计算的内容
            Console.WriteLine("Adder Add( {0} + {1} )", d1, d2);
            //返回值
            return d1 + d2;
        }

        #endregion
    }

    class program
    {
        static void Main()
        {
            //创建一个信道对象
            HttpChannel channel = new HttpChannel(65100);
            //注册信道对象
            ChannelServices.RegisterChannel(channel, false);
            //提供注册类型、URI地址、激活对象的模式
            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(Adder),
                "AddService",
                WellKnownObjectMode.SingleCall);
            //提示等待
            Console.WriteLine("press a key to stop the server...");
            //主线程挂起
            Console.ReadLine();
        }
    }

}

 

3.建立客户端,引用上面的接口程序集,客户端代码如下:

 

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

using remotinginterfaces;

namespace remotingclient
{
    class program
    {
        static void Main()
        {
            //建立信道对象
            HttpChannel channel = new HttpChannel(0);
            //注册信道
            ChannelServices.RegisterChannel(channel, false);
            //使用给定的 注册类型、URI地址、激活对象的模式 为已知对象创建一个代理
            MarshalByRefObject objeRef = (MarshalByRefObject)
            RemotingServices.Connect(
            typeof(IAdder),
            "http://localhost:65100/AddService");
            //将代理对象强制转换为需要的代理类型(引用了IAdder接口)
            IAdder obj = objeRef as IAdder;
            for (int i = 0; i < 5000; i++)
            {
                //进行5000次循环调用代理对象来得到结果(并观察服务器端的垃圾收集情况)
                double d = obj.Add(3.0, 4.0);
                //输出结果
                Console.WriteLine("返回的值为:{0}", d);
            }
            //主线程挂起
            Console.ReadLine();
        }
    }
}

原创粉丝点击