当前位置: 移动技术网 > IT编程>开发语言>c# > C# NetRemoting实现双向通信

C# NetRemoting实现双向通信

2019年07月18日  | 移动技术网IT编程  | 我要评论

闲来无事想玩玩双向通信,实现类似qq的互发消息的功能。于是乎开始学习.net remoting.

.net remoting 是由客户端通过remoting,访问通道以获得服务端对象,再通过代理解析为客户端对象来实现通信的。也就是说对象是由服务端创建的。

先上代码

首先是icommand库

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace icommand
{
  public interface iremotingobject
  {
    event sendhandler clienttoserver;
    event receivehandler servertoclient;
    event userchangedhandler login;
    event userchangedhandler exit;
    /// <summary>
    /// 加法运算
    /// </summary>
    /// <param name="x1">参数1</param>
    /// <param name="x2">参数2</param>
    /// <returns></returns>
    string sum(int x1, int x2);
    /// <summary>
    /// 获取服务端事件列表
    /// </summary>
    delegate[] getservereventlist();
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="info"></param>
    /// <param name="toname"></param>
    void toserver(object info, string toname);
    /// <summary>
    /// 接受信息
    /// </summary>
    /// <param name="info"></param>
    /// <param name="toname"></param>
    void toclient(object info, string toname);
    void tologin(string name);
    void toexit(string name);
  }
  /// <summary>
  /// 客户端发送消息
  /// </summary>
  /// <param name="info">信息</param>
  /// <param name="toname">发送给谁,""表示所有人,null表示没有接收服务器自己接收,其他表示指定某人</param>
  public delegate void sendhandler(object info, string toname);
  /// <summary>
  /// 客户端接收消息
  /// </summary>
  /// <param name="info">信息</param>
  /// <param name="toname">发送给谁,""表示所有人,null表示没有接收服务器自己接收,其他表示指定某人</param>
  public delegate void receivehandler(object info, string toname);
  /// <summary>
  /// 用户信息事件
  /// </summary>
  /// <param name="name">用户名</param>
  public delegate void userchangedhandler(string name);
}

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace icommand
{
  public class swapobject : marshalbyrefobject
  {

    public event receivehandler swapservertoclient 
    {
      add { _receive += value; }
      remove { _receive -= value; }
    }
    /// <summary>
    /// 接受信息
    /// </summary>
    /// <param name="info"></param>
    /// <param name="toname"></param>
    public void toclient(object info, string toname)
    {
      if (_receive != null)
        _receive(info, toname);
    }
    //无限生命周期 
    public override object initializelifetimeservice()
    {
      return null;
    }

    private receivehandler _receive;
  } 
}

第一个类就是定义一些接口,和一些委托,没有实质性的东西。

第二个类是定义了上一个接口类中的toclient的事件和方法,作用之后会讲到。

然后就是集成icommand接口的实质性的数据类

using system;
using system.collections.generic;
using system.linq;
using system.text;
using icommand;

namespace netremoting
{
  public class remotingobject : marshalbyrefobject, iremotingobject
  {
    /// <summary>
    /// 发送事件
    /// </summary>
    public event sendhandler clienttoserver
    {
      add { _send += value; }
      remove { _send -= value; }
    }
    /// <summary>
    /// 接收消息事件
    /// </summary>
    public event receivehandler servertoclient;
    /// <summary>
    /// 发送事件
    /// </summary>
    public event userchangedhandler login
    {
      add { _login += value; }
      remove { _login -= value; }
    }
    /// <summary>
    /// 发送事件
    /// </summary>
    public event userchangedhandler exit
    {
      add { _exit += value; }
      remove { _exit -= value; }
    }
    /// <summary>
    /// 加法运算
    /// </summary>
    /// <param name="x1">参数1</param>
    /// <param name="x2">参数2</param>
    /// <returns></returns>
    public string sum(int x1, int x2)
    {
      return x1 + "+" + x2 + "=" + (x1 + x2);
    }
    /// <summary>
    /// 绑定服务端向客户端发送消息的事件方法
    /// </summary>
    /// <param name="receive">接收事件</param>
    public delegate[] getservereventlist()
    {
      return this.servertoclient.getinvocationlist();
    }
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="info"></param>
    /// <param name="toname"></param>
    public void toserver(object info, string toname)
    {
      if (_send != null)
        _send(info, toname);
    }
    /// <summary>
    /// 接收消息
    /// </summary>
    /// <param name="info"></param>
    /// <param name="toname"></param>
    public void toclient(object info, string toname)
    {
      if (_receive != null)
        _receive(info, toname);
    }
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="name">用户名</param>
    public void tologin(string name)
    {
      if (!_namehash.contains(name))
      {
        _namehash.add(name);
        if (_login != null)
          _login(name);
      }
      else
      { throw new exception("用户已存在"); }
    }
    /// <summary>
    /// 退出
    /// </summary>
    /// <param name="name">用户名</param>
    public void toexit(string name)
    {
      if (_namehash.contains(name))
      {
        _namehash.remove(name);
        if (_exit != null)
          _exit(name);
      }
    }

    private sendhandler _send;
    private receivehandler _receive;
    private userchangedhandler _login;
    private userchangedhandler _exit;
    private hashset<string> _namehash = new hashset<string>();
  }
}

该类集成了marshalbyrefobject

由于remoting传递的对象是以引用的方式,因此所传递的远程对象类必须继承marshalbyrefobject。msdn对marshalbyrefobject的说明是:marshalbyrefobject 是那些通过使用代理交换消息来跨越应用程序域边界进行通信的对象的基类。不是从 marshalbyrefobject 继承的对象会以隐式方式按值封送。当远程应用程序引用一个按值封送的对象时,将跨越远程处理边界传递该对象的副本。因为您希望使用代理方法而不是副本方法进行通信,因此需要继承marshallbyrefobject。

该类主要是定义了一些方法用于客户端触发事件,toserver,toclient,tologin,toexit以及一些事件,客户端发向服务端的事件,和服务端发向客户端的事件。

_namehash 只是记录有哪些用户登录了。

接下去就是客户端和服务端了。

首先服务端:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.runtime.remoting;
using system.runtime.remoting.channels;
using system.runtime.remoting.channels.http;
using netremoting;
using system.collections;
using system.runtime.serialization.formatters;
using icommand;

namespace netremotingserver
{
  public partial class server : form
  {
    public server()
    {
      initializecomponent();
      initialize();
    }
    /// <summary>
    /// 注册通道
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void server_load(object sender, eventargs e)
    {

      channelservices.registerchannel(_channel, false);
      //remotingconfiguration.registerwellknownservicetype(typeof(remotingobject), "summessage", wellknownobjectmode.singleton); //a方案
      /*将给定的 system.marshalbyrefobject 转换为具有指定 uri 的 system.runtime.remoting.objref 类的实例。
       objref :存储生成代理以与远程对象通信所需要的所有信息。*/
      objref objref = remotingservices.marshal(_remotingobject, "summessage");//b方案
      _remotingobject.clienttoserver += (info, toname) =>
      {
        rxtinfo.invoke((methodinvoker)(() => { rxtinfo.appendtext(info.tostring() + "\r\n"); }));
        sendtoclient(info, toname);
      };
      _remotingobject.login += (name) =>
      {
        rxtinfo.invoke((methodinvoker)(() => { rxtinfo.appendtext(name + " 登录" + "\r\n"); }));
      };
      _remotingobject.exit += (name) =>
      {
        rxtinfo.invoke((methodinvoker)(() => { rxtinfo.appendtext(name + " 退出" + "\r\n"); }));
      };
    }
    /// <summary>
    /// 注销通道
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void server_formclosing(object sender, formclosingeventargs e)
    {
      if (_channel != null)
      {
        _channel.stoplistening(null);
        channelservices.unregisterchannel(_channel);
      }
    }
    /// <summary>
    /// 广播消息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnsend_click(object sender, eventargs e)
    {
      sendtoclient(txtsend.text, txtname.text);
    }
    /// <summary>
    /// 发送消息到客户端
    /// </summary>
    /// <param name="info"></param>
    /// <param name="toname"></param>
    private void sendtoclient(object info, string toname)
    {
      //foreach (var v in _remotingobject.getservereventlist())
      //{
      //  try
      //  {
      //    receivehandler receive = (receivehandler)v;
      //    receive.begininvoke(info, toname, null, null);
      //  }
      //  catch
      //  { }
      // }
      _remotingobject.toclient(txtsend.text, txtname.text);
    }
    /// <summary>
    /// 初始化
    /// </summary>
    private void initialize()
    {
      //设置反序列化级别 
      binaryserverformattersinkprovider serverprovider = new binaryserverformattersinkprovider();
      binaryclientformattersinkprovider clientprovider = new binaryclientformattersinkprovider();
      serverprovider.typefilterlevel = typefilterlevel.full;//支持所有类型的反序列化,级别很高 
      idictionary idic = new dictionary<string, string>();
      idic["name"] = "serverhttp";
      idic["port"] = "8022";
      _channel = new httpchannel(idic, clientprovider, serverprovider);
      _remotingobject = new remotingobject();
    }

    httpchannel _channel;
    private remotingobject _remotingobject;


  }
}

然后客户端:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.runtime.remoting;
using system.runtime.remoting.channels;
using system.runtime.remoting.channels.http;
using icommand;
using system.runtime.serialization.formatters;
using system.collections;

namespace netremotingclient
{
  public partial class client : form
  {
    public client()
    {
      initializecomponent();
    }
    /// <summary>
    /// 注册通道
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void client_load(object sender, eventargs e)
    {
      try
      {
        //设置反序列化级别 
        binaryserverformattersinkprovider serverprovider = new binaryserverformattersinkprovider();
        binaryclientformattersinkprovider clientprovider = new binaryclientformattersinkprovider();
        serverprovider.typefilterlevel = typefilterlevel.full;//支持所有类型的反序列化,级别很高 
        //信道端口 
        idictionary idic = new dictionary<string, string>();
        idic["name"] = "clienthttp";
        idic["port"] = "0";
        httpchannel channel = new httpchannel(idic, clientprovider, serverprovider);
        channelservices.registerchannel(channel, false);
        _remotingobject = (iremotingobject)activator.getobject(typeof(iremotingobject), "http://localhost:8022/summessage");
        //_remotingobject.servertoclient += (info, toname) => { rtxmessage.appendtext(info + "\r\n"); };
        swapobject swap = new swapobject();
        _remotingobject.servertoclient += swap.toclient;
        swap.swapservertoclient += (info, toname) =>
        {
          rtxmessage.invoke((methodinvoker)(() =>
        {
          if (toname == txtlogin.text || toname == "")
            rtxmessage.appendtext(info + "\r\n");
        }));
        };
      }
      catch (exception ex)
      { messagebox.show(ex.message); }
    }
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnlogin_click(object sender, eventargs e)
    {
      try
      {
        if (txtlogin.text == "")
          throw new exception("用户名不得为空");
        _remotingobject.tologin(txtlogin.text);
      }
      catch (exception ex)
      {
        messagebox.show(ex.message);
      }
    }
    /// <summary>
    /// 退出
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void client_formclosing(object sender, formclosingeventargs e)
    {
      try
      {
        _remotingobject.toexit(txtlogin.text);
      }
      catch
      { }
    }
    /// <summary>
    /// 发送
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnsend_click(object sender, eventargs e)
    {
      //rtxmessage.appendtext(_remotingobject.sum(2, 4) + "\r\n");
      _remotingobject.toserver(txtsend.text, txtname.text);
    }


    private iremotingobject _remotingobject;

  }
}

服务端实现步骤:

1、注册通道

要跨越应用程序域进行通信,必须实现通道。如前所述,remoting提供了ichannel接口,分别包含tcpchannel和httpchannel两种类型的通道。这两种类型除了性能和序列化数据的格式不同外,实现的方式完全一致,因此下面我们就以tcpchannel为例。

注册tcpchannel,首先要在项目中添加引用“system.runtime.remoting”,然后using名字空间:system.runtime.remoting.channel.tcp。代码如下:

tcpchannel channel = new tcpchannel(8022);
channelservices.registerchannel(channel);

在实例化通道对象时,将端口号作为参数传递。然后再调用静态方法registerchannel()来注册该通道对象即可。

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);

客户端实现步骤:

1、注册通道:

tcpchannel channel = new tcpchannel();
channelservices.registerchannel(channel);

注意在客户端实例化通道时,是调用的默认构造函数,即没有传递端口号。事实上,这个端口号是缺一不可的,只不过它的指定被放在后面作为了uri的一部分。

2、获得远程对象

与服务器端相同,不同的激活模式决定了客户端的实现方式也将不同。不过这个区别仅仅是wellknown激活模式和客户端激活模式之间的区别,而对于singleton和singlecall模式,客户端的实现完全相同。

(1) wellknown激活模式

要获得服务器端的知名远程对象,可通过activator进程的getobject()方法来获得:

serverremoteobject.serverobject serverobj = (serverremoteobject.serverobject)activator.getobject(
       typeof(serverremoteobject.serverobject), "tcp://localhost:8080/servicemessage");

首先以wellknown模式激活,客户端获得对象的方法是使用getobject()。其中参数第一个是远程对象的类型。第二个参数就是服务器端的uri。如果是http通道,自然是用http://localhost:8022/servicemessage了。因为我是用本地机,所以这里是localhost,你可以用具体的服务器ip地址来代替它。端口必须和服务器端的端口一致。后面则是服务器定义的远程对象服务名,即applicationname属性的内容。

//设置反序列化级别 
        binaryserverformattersinkprovider serverprovider = new binaryserverformattersinkprovider();
        binaryclientformattersinkprovider clientprovider = new binaryclientformattersinkprovider();
        serverprovider.typefilterlevel = typefilterlevel.full;//支持所有类型的反序列化,级别很高 
        //信道端口 
        idictionary idic = new dictionary<string, string>();
        idic["name"] = "clienthttp";
        idic["port"] = "0";
        httpchannel channel = new httpchannel(idic, clientprovider, serverprovider);

从上述代码中可以看到注册方式有所变化,那是因为客户端注册服务端的事件时会报错“不允许类型反序列化”。

还有一个需要注意的是:

objref objref = remotingservices.marshal(_remotingobject, "summessage");
//remotingconfiguration.registerwellknownservicetype(typeof(remotingobject), "summessage", wellknownobjectmode.singleton);
//调用系统自动创建,导致拿不到_remotingobject对象的实例化,这样后期绑定事件就无法操作下去了,当然也可以直接静态事件绑定,这样就不需要手动实例化对象了

通过该方法手动创建_remotingobject这个对象的实例化。

然后之前讲到了一个swapobject这个类,这个类的作用是事件交换。

 

_remotingobject.servertoclient +=方法();
//这样因为这个方法是客户端的,服务端无法调用,所以需要一个中间转换的
 swapobject swap = new swapobject();//先创建一个swap对象
 _remotingobject.servertoclient += swap.toclient;//然后服务端事件发信息给swap,然后swap再通过事件发消息给客户端,swap是客户端创建的所以可以发送,而swap是服务端的类,所以服务端也能识别,swap起到了中间过渡的作用
 swap.swapservertoclient +=方法();

以上是两天.net remoting的学习结果。

最后附上源码:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网