.Net Remoting技术在局域网内的分布式应用中使用比较广泛,希望通过这一系列的文章,分享我对.net remoting的应用和了解,不当之处,欢迎指正。

这一节我们先来看看如何创建一个简单的.net remoting分布式应用。

要点:

1.  创建远程对象

2.  创建Server

3.  创建Client

 

定义业务对象接口:

 

    public interface ICustomersBO

    {

        string GetCustomerNameByID(int customerID);

    }

 

 

实现业务对象接口

 

    public class CustomersBO:ICustomersBO

    {

        #region ICustomersBO Members

 

        public string GetCustomerNameByID(int customerID)

        {

            return "Blauer See Delikatessen";

        }

 

        #endregion

    }

 

定义远程对象:

 

    public class RemotingCustomersBO:MarshalByRefObject,ICustomersBO

    {

        private ICustomersBO _customersBO;

 

        public RemotingCustomersBO()

        {           

            this._customersBO = new CustomersBO();

        }

 

        #region ICustomersBO Members

 

        public string GetCustomerNameByID(int customerID)

        {

            return this._customersBO.GetCustomerNameByID(customerID);

        }

 

        #endregion

    }

 

或许到这儿,有的朋友会问,为什么不直接定义一个远程业务对象实现业务接口,事实上在项目中,同一个业务对象往往会有不同的部署方式,我们可以将它封装成remoting的远程对象,也可以将它封装成web service,这样做的目的,只是为了扩展的需要,不过这已经超越了本节的话题,就到此打住。

 

创建Remoting服务端

 

服务端需要注册通道和端口,以及发布远程对象,代码如下。

    class Program

    {

        static void Main(string[] args)

        {

HttpChannel httpChannel = new HttpChannel(1234);

              ChannelServices.RegisterChannel(httpChannel, false);

              WellKnownObjectMode mode = WellKnownObjectMode.SingleCall;

              WellKnownServiceTypeEntry entry = new WellKnownServiceTypeEntry(

                typeof(RemotingCustomersBO), "CustomersBO.soap", mode);

              RemotingConfiguration.RegisterWellKnownServiceType(entry);

              Console.WriteLine("Server starts as Sao. Press Enter to exit...");

              Console.ReadLine();

        }

}  

 

 

创建Remoting客户端:

 

    class Program

    {

        static void Main(string[] args)

        {

            HttpChannel httpChannel = new HttpChannel();

            ChannelServices.RegisterChannel(httpChannel, false);

            WellKnownClientTypeEntry entry = new WellKnownClientTypeEntry(

                typeof(RemotingCustomersBO), "http://localhost:1234/CustomersBO.soap");

            RemotingConfiguration.RegisterWellKnownClientType(entry);

            ICustomersBO customersBO = new RemotingCustomersBO();

            Console.WriteLine(customersBO.GetCustomerNameByID(3));

            Console.ReadLine();                       

        }

}

 

 

至此,一个简单的分布式应用就完成了,你可以直接下载本节示例中工程源代码RemotingExample1.rar运行,工程开发环境是VS2005+.Net Framwork2.0

 

注:本系列文章乃作者原创,转载请注明出处,谢谢。

posted on 2007-06-22 15:43  ksxs  阅读(280)  评论(0编辑  收藏  举报