Remoting 实现 视图(UI)和逻辑层(BLL)前后台分离

原参考文档:https://blog.csdn.net/Maybe_ch/article/details/82805115

1.什么是Remoting
简而言之,我们可以将其看作是一种分布式处理方式。从微软的产品角度来看,可以说 Remoting 就是 DCOM的一种升级,它改善了很多功能,并极好的融合到.NET平台下。Microsoft? .NET Remoting 提供了一种允许对象通过应用程序域与另一对象进行交互的框架。这也正是我们使用 Remoting 的原因。
在 Remoting 中是通过通道(channel)来实现两个应用程序域之间对象的通信的。 首先,客户端通过Remoting,访问通道以获得服务端对象,再通过代理解析为客户端对象。这就提供一种可能性,即以服务的方式来发布服务器对象。远程对象代码可以运行在服务器上(如服务器激活的对象和客户端激活的对象),然后客户端再通过 Remoting 连接服务器,获得该服务对象并通过序列化在客户端运行。
在 Remoting 中,对于要传递的对象,设计者除了需要了解通道的类型和端口号之外,无需再了解数据包的格式。但必须注意的是,客户端在获取服务器端对象时,并不是获得实际的服务端对象,而是获得它的引用。这既保证了客户端和服务器端有关对象的松散耦合,同时也优化了通信的性能。
---------------------

2.代码实现

BLL(服务器端代码):

1)服务器端通道对接代码:

 namespace ServiceConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //声明TcpServerChannel类型的静态字段channels
            TcpServerChannel channels;
            //创建新的TcpServerChannel对象,端口号为3000,引用为channels
            channels = new TcpServerChannel(3000);
            //将channels注册到信道服务
            ChannelServices.RegisterChannel(channels, false);
            //创建知名服务类型的对象,传递远程对象的类型,对象URI和激活对象的枚举成员
            RemotingConfiguration.RegisterWellKnownServiceType(typeof( MyObject), "MyUri", WellKnownObjectMode.Singleton);
            //信息提示,当用户输入字符,则结束程序
            Console.WriteLine("======服务器端已启动======");
            Console.Read();
          
        }
    }
}

 

2)服务器端逻辑实现类库代码:

 
namespace ClassLibrary3
{
    public class MyObject : MarshalByRefObject
    {
        public MyObject()
        {

        }
        public string Add(int a, int b)
        {
            return ("=====MyObject liberty 调用时间:===="+DateTime.Now.ToShortDateString()+"    " + a + b);
        }
    }
}

 

UI 视图层代码:

1 )UI通道创建访问:
namespace ClientConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {//声明TcpClientChannel类型的字段channels
            TcpClientChannel channelc;
            //声明MyObject类型的字段MyObject
            MyObject remoteObject;
            //创建TcpClientChannel对象,引用为channelc
            channelc = new TcpClientChannel();
            //将channels注册到信道服务
            ChannelServices.RegisterChannel(channelc, false);
            //创建远程对象
            remoteObject = (MyObject)Activator.GetObject(typeof(MyObject), "tcp://127.0.0.1:3000/MyUri");
            //调用服务的方法
            string str=remoteObject.Add(5, 6);
            Console.WriteLine("调用成功");
            Console.WriteLine(str);
            Console.Read();
           
        }
    }
}

3 运行结果:

 

posted @ 2019-03-27 14:01  过河小斌  阅读(255)  评论(0)    收藏  举报