【Remoting-5代码实现】

服务端

class RemotingServiceHelper
{
    private static string m_protocolType;
    private static string urlString = "{0}://{1}:{2}/{3}";
    /// <summary>
    /// 注册Ichannel通道
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static bool RegisterChannel(ChannelType type)
    {
        try
        {
            IChannel channel;
            IDictionary tables=new Hashtable();
            tables["port"] = 9011;
            switch (type)
            {
                case ChannelType.HttpChannel:
                    tables["name"] = "HttpChannel";
                    channel=new HttpChannel(tables,new SoapClientFormatterSinkProvider(),
                        new SoapServerFormatterSinkProvider());
                    m_protocolType = "http";
                    break;
                case ChannelType.TcpChannel:
                    tables["name"] = "TcpChannel";
                    channel=new TcpChannel(tables,new BinaryClientFormatterSinkProvider(),
                        new BinaryServerFormatterSinkProvider() );
                    m_protocolType = "tcp";
                    break;
                case ChannelType.IpcChannl:
                    tables["name"] = "IpcChannel";
                    channel=new IpcChannel(tables,new BinaryClientFormatterSinkProvider(),
                        new BinaryServerFormatterSinkProvider());
                    m_protocolType = "ipc";
                    break;
                default:
                    channel = null;
                    return false;

            }
            ChannelServices.RegisterChannel(channel,false);
            Console.WriteLine("服务注册成功!端口号为:{0},通道类型为{1}", tables["port"],type);
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
          //  channel = null;
            return false;
        }
    }

    public static bool ActivatedServiceObject(ActivatedType type)
    {
        RemotingConfiguration.ApplicationName = "RemotingService";
        string url=String.Empty;
        string objUri = type.ToString();
        switch (type)
        {
            case ActivatedType.Client:
                Console.WriteLine("激活方式:客户端激活");
                //在服务端上,指定使用客户端激活方式激活远程服务对象
                RemotingConfiguration.RegisterActivatedServiceType(typeof(ServiceObj));
                url = string.Format(urlString, m_protocolType, IPAddress.Loopback, 9011,
                    RemotingConfiguration.ApplicationName);
             break;
            case ActivatedType.ServiceSingleCall:
             Console.WriteLine("激活方式:服务端ServiceSingleCall激活");
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(ServiceObj),"ServiceSingleCall",WellKnownObjectMode.SingleCall);
                url = string.Format(urlString+"/{4}", m_protocolType, IPAddress.Loopback, 9011,
                    RemotingConfiguration.ApplicationName, objUri);
                break;
            case ActivatedType.ServiceSingleton:
                Console.WriteLine("激活方式:服务端ServiceSingleton激活");
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(ServiceObj), "ServiceSingleton", WellKnownObjectMode.Singleton);
                url = string.Format(urlString + "/{4}", m_protocolType, IPAddress.Loopback, 9011,
                   RemotingConfiguration.ApplicationName, objUri);
               break;
            default :
                return false;
        }
        Console.WriteLine("远程对象的Url地址为:{0}",url);
        return true;
    }
}

enum ChannelType
{
    TcpChannel,
    HttpChannel,
    IpcChannl,
}

enum ActivatedType
{
    Client,
    ServiceSingleton,
    ServiceSingleCall,
}
class Program
   {
       static void Main(string[] args)
       {
           Console.WriteLine("注册Ichannel通道");
           if (RemotingServiceHelper.RegisterChannel(ChannelType.HttpChannel))
           {
              // Console.WriteLine("通道注册成功,通道类型为{0}",ChannelType.TcpChannel);
               if (RemotingServiceHelper.ActivatedServiceObject(ActivatedType.ServiceSingleton))
               {
                   Console.WriteLine("远程服务对象激活成功!");
                   Console.ReadKey();
               }
           }
       }
   }

客户端:

【注意对服务程序集的引用或是分离】

class ClientProxy
   {
       private string urlString = "{0}://{1}:{2}/{3}";
       private ServiceObj _serviceObj;

       private string m_protocol;
       private string m_appName;
       private ActivatedType m_activatedType;
       public ClientProxy(string protocol, string appName, ActivatedType activatedType)
       {
           m_protocol = protocol;
           m_appName = appName;
           m_activatedType = activatedType;
       }

       public ServiceObj ServiceObj
       {
           get
           {
               if (ActivatorServiceObj())
               {
                   return _serviceObj;
               }
               else
               {
                   Console.WriteLine("激活远程对象失败");
                   return null;
               }

           }
       }

       private bool ActivatorServiceObj()
       {
           string url = GetUrlString();
           // string url = "";
           try
           {
               //  _serviceObj = (ServiceObj)Activator.GetObject(typeof(ServiceObj), url);
               switch (m_activatedType)
               {
                   case ActivatedType.Client:
                       //先激活远程对象,再调用构造函数创建对象
                       RemotingConfiguration.RegisterActivatedClientType(typeof(ServiceObj), url);
                       _serviceObj = new ServiceObj();
                       break;
                   case ActivatedType.ServiceSingleCall:
                       _serviceObj = (ServiceObj)RemotingServices.Connect(typeof(ServiceObj), url);
                       break;
                   case ActivatedType.ServiceSingleton:
                       _serviceObj = (ServiceObj)Activator.GetObject(typeof(ServiceObj), url);
                       break;
               }
               return true;
           }
           catch (Exception e)
           {
               Console.WriteLine(e);
               return false;
           }
       }

       private string GetUrlString()
       {
           string url = string.Empty;
           switch (m_activatedType)
           {
               case ActivatedType.Client:
                   url = string.Format(urlString, m_protocol, IPAddress.Loopback, 9011,
                      m_appName);
                   break;
               case ActivatedType.ServiceSingleCall:
                   url = string.Format(urlString + "/{4}", m_protocol, IPAddress.Loopback, 9011,
                      m_appName, "ServiceSingleCall");
                   break;
               case ActivatedType.ServiceSingleton:
                   url = string.Format(urlString + "/{4}", m_protocol, IPAddress.Loopback, 9011,
                      m_appName, "ServiceSingleton");
                   break;
           }
           return url;
       }

   }

   enum ChannelType
   {
       TcpChannel,
       HttpChannel,
       IpcChannl,
   }

   enum ActivatedType
   {
       Client,
       ServiceSingleton,
       ServiceSingleCall,
   }
class Program
  {
      static void Main(string[] args)
      {
          ClientProxy proxy = new ClientProxy("http", "RemotingService", ActivatedType.ServiceSingleton);
          ServiceObj obj = proxy.ServiceObj;
          if (obj != null)
          {
              obj.PrintAppDomain();
              obj.PrintAppDomain();
              obj.ShowCount("张三");
              Console.WriteLine(obj.GetSum(10, 12));
              Console.WriteLine(obj.GetStrInfo("张三"));
              Console.WriteLine("count:{0}", obj.Count);
          }
          Console.WriteLine();
          ClientProxy proxy2 = new ClientProxy("http", "RemotingService", ActivatedType.ServiceSingleton);
          ServiceObj obj2 = proxy2.ServiceObj;
          if (obj2 != null)
          {
              obj2.PrintAppDomain();
              obj2.PrintAppDomain();
              obj2.ShowCount("张三");
              Console.WriteLine(obj.GetSum(332, 12));
              Console.WriteLine(obj.GetStrInfo("李四"));
              Console.WriteLine("count:{0}", obj.Count);
          }

          Console.ReadKey();
      }
  }

远程服务对象

  public class ServiceObj:MarshalByRefObject,IServiceObj
    {
        private int count = 0;
        public ServiceObj()
        {
            Console.WriteLine("服务对象的构造函数");
            Console.WriteLine();
        }

        public int Count
        {
            get { return count; }
        }

        public void ShowCount(string name)
        {
            count++;
            Console.WriteLine("{0},count的值为{1}",name,Count);
        }

        public void PrintAppDomain()
        {
           // AppDomain currentDomain = AppDomain.CurrentDomain;
            AppDomain currentDomain = Thread.GetDomain();//获取当前线程所在的应用程序域
            Console.WriteLine(currentDomain.FriendlyName);
        }

        public int GetSum(int a, int b)
        {
            Console.WriteLine("A+B={0}",a+b);
            return a + b;
        }

        public string GetStrInfo(string arg)
        {
            Console.WriteLine(arg);
            return string.Format("返回一个字符串加参数{0}", arg);
        }

    }
时间: 2024-08-05 07:04:02

【Remoting-5代码实现】的相关文章

.net core 2.0学习笔记(六):Remoting核心类库RealProxy迁移

在学习.net core的过程中,我们已经明确被告知,Remoting将不会被支持.官方的解释是,.net framework 类型包含了太多的Runtime的内容,是一个非常重量级的服务实现,已被确定为一项有问题的体系结构.说白了就是迁移的难度很大,.net core中直接不提供了.微软的建议是,如果是进程内或跨进程通讯,建议我们使用 Pipes或者内存映射文件(Memory Mapped Files).如果是机器间的调用,建议我们采用网络通讯的方案,比如HTTP.WCF等. 好吧,既然微软官

分布式应用处理方式 - Remoting

分布式应用程序 所谓分布式计算是一门计算机科学,它研究如何把一个需要非常巨大的计算能力才能解决的问题分成许多小的部分,然后把这些部分分配给许多计算机进行处理,最后把这些计算结果综合起来得到最终的结果. 分布式的优势 地域分散性 比如银行系统,总行与各分行处于不同的城市或城市中的各个地区,在业务上它们需要处理各自的数据,也需要彼此之间的交换和处理,这就需要分布式的系统. 满足扩充性 如果一个组织机构需要增加新的相对自主的组织单位来扩充机构,则分布式数据库系统可以在对当前机构影响最小的情况下进行扩充

Seam - 无缝集成 JSF

第 1 部分: 为 JSF 量身定做的应用程序框架 ----> 发现 Seam 对 JSF 生命周期特有的增强 JavaServer Faces (JSF) 是用于 Java? Web 应用程序的第一个标准化的用户界面框架.而 Seam 是一个扩展 JSF 的强大的应用程序框架.在这个由三部分组成的新系列中的第一篇文章中,发现这两种框架之间的互补性.Dan Allen 介绍了 Seam 对 JSF 生命周期的增强,包括上下文状态管理. RESTful URL.Ajax remoting.适当的异

错误和问题解决的成本

问题描写叙述 错误 数据收集 根本原因 版本号   组件:数据修复           在一个实际成本组织中,(平均,先进先出,后进先出) 一个或更 多的下面情况可能发生: 1.导航到物料成本历史表单上的数量信息,与现有量表单的数量不匹配的记录 2. 一些物料前期已计成本的数量与前面的事务处理历史表单的数量不匹配 3. 全部的库存值报表与事务处理值报表不匹配 4. 存货层次成本更新表单的总数量与现有量数量表单不匹配(只在先进先出/后进先出) 5.这些症状的不论什么一个意味着 MMT-CQL不匹配

.Net remoting方法实现简单的在线升级(上篇:更新文件)

一.前言:       最近做一个简单的在线升级Demo,使用了微软较早的.Net Remoting技术来练手. 简单的思路就是在服务器配置一个Remoting对象,然后在客户端来执行Remoting对象中的方法. 过程: (1) 读取本地dll文件的名称与版本号,与服务器的进行对比 (2) 确认需要升级的文件名称与版本号并告诉服务器,服务器将其复制到一个临时文件夹并压缩成zip (3) 将服务器的zip下载到本地的临时文件夹,并解压. 定义服务器端为UpdateServer,其配置文件为: <

WCF分布式开发必备知识(2):.Net Remoting

.Net Remoting技术,我们可以将其看作是一种分布式处理方式.作为应用程序之间通信的一种机制,.Net Remoting与MSMQ消息队列不同,它不支持离线脱机消息,另外只适合.Net平台间程序的通信.从微软的产品角度来看,可以说Remoting就是分布式组件DCOM的一种升级,它改善了很多功能,并极好的融合到.Net平台下..NET Remoting 提供了一种允许对象通过应用程序域与另一对象进行交互的框架.这也正是我们使用Remoting的原因.为什么呢?在Windows操作系统中,

rocketMQ的运行示例代码

rocketMQ的示例代码 1 import com.alibaba.rocketmq.client.exception.MQBrokerException; 2 import com.alibaba.rocketmq.client.exception.MQClientException; 3 import com.alibaba.rocketmq.client.producer.DefaultMQProducer; 4 import com.alibaba.rocketmq.client.pr

Castle 整合.NET Remoting

今天研究了一下Castle的Remoting Facility.记录如下: 微软以前使用COM/DCOM的技术来处理分布式系统架构,通过Client端的Proxy代理程序来呼叫远程Server机器上的对象..NET Framework则使用.NET Remoting或Web Services技术来实作分布式处理的工作概念:在这里针对.NET Remoting的设计架构做一个初步的简介和Castle整合示例. .NET Framework提供了多种的机制来支持Remoting,如: .利用Chan

用Spring.Services整合 thrift0.9.2生成的wcf中间代码-复杂的架构带来简单的代码和高可维护性

参考页面: http://www.yuanjiaocheng.net/CSharp/csharp-class.html http://www.yuanjiaocheng.net/CSharp/csharp-variable.html http://www.yuanjiaocheng.net/CSharp/Csharp-data-types.html http://www.yuanjiaocheng.net/CSharp/cshart-value-reference-type.html http:

读 《.Net 之美》解析.Net Remoting (应用程序域)-- Part.1

读 <.Net 之美>解析.Net Remoting (应用程序域)-Part1 理解 .Net Remoting 前言: 看张子阳老师的文章,总是给自己很大的信心,这个专题基本上以张老师的书为主,我整理书中的主要代码,补充了些自己的理解,希望和大家一起学习:) 背景: 分布式开发是一个重要的方向,前段时间做公司的一个爬虫项目,多个客户端和服务端的交互,使我产生了浓厚的兴趣,WCF.WebService.Socket也是常用 的技术..Net Remoting 在.NetFrameWork 3