使用websocket心跳检测连接状态

2,898 阅读1分钟

作者在开发中遇到这样一个问题,客户端程序因为网络原因(或者其他)失去了与activemq(可见作者相关分享)的通信,现场导致连接断开的原因往往十分复杂,因此在弱网环境或者网络暂时断连的情况下,我们需要一套稳定的重连机制来保证在网络不稳定的时候,客户端和服务端能够重连,继续通信。

心跳机制

  1. 什么是心跳机制
  • 这个概念可能需要一点时间理解一下,其实可以简单理解为一个信号,客户端和服务端相互感应,保证彼此还活着,避免丢包发生,详细概念可以看一下大佬们的分享,本人负责搬运。
https://blog.csdn.net/qq_39989929/article/details/89738307
https://www.cnblogs.com/buxiugangzi/p/11379883.html
  1. 解析stompjs连接MQ的内部实现
  • 对websocket增加一层协议头的封装
 
 Stomp = {
    VERSIONS: {
      V1_0: '1.0',
      V1_1: '1.1',
      V1_2: '1.2',
      supportedVersions: function() {
        return '1.1,1.0';
      }
    },
    client: function(url, protocols) {
      var klass, ws;
      if (protocols == null) {
        protocols = ['v10.stomp', 'v11.stomp'];
      }
      klass = Stomp.WebSocketClass || WebSocket;
      ws = new klass(url, protocols);
      return new Client(ws);
    },
    over: function(ws) {
      return new Client(ws);
    },
    Frame: Frame
  };
  1. 重连机制
  • 客户端、服务端配置心跳
    //客户端:
    let client = Stomp.client(ws);
    // 设置心跳响应时间 超时不响应就会触发重连
    // stompjs 设置的是10秒钟响应时间
    // client.heartbeat.outgoing = 0;
    // client.heartbeat.incoming = 0;
  • 在错误回调函数使用定时器重连
    //当心跳失去响应时,stompjs会触发ws.close(), 关闭连接
    //只需要在错误callback中进行重连即可
    //建立Mq连接
    createMqConet() {
  
      let ws = 'ws://192.168.199.252:61614/stomp';

      let client = Stomp.client(ws);

      // //禁用心跳
      // client.heartbeat.outgoing = 0;
      // client.heartbeat.incoming = 0;

      // Declare on_connect
      let on_connect = function() {
       //...
      };

      let on_error = () => {
        //防止多次触发重连
        if (this.createMqConet.lockReconnect) { 
          return;
        }
        this.createMqConet.lockReconnect = true;
        this.timer && clearTimeout(this.timer);
        //10s进行一次重连
        this.timer = setTimeout(() => {
          this.createMqConet.lockReconnect = false;
          this.createMqConet();
        }, 10000);
      };

      client.connect("", "", on_connect, on_error, "");
    }
  },
      

看看内部的处理:

有兴趣的可自行研究一下源码 https://github.com/jmesnil/stomp-websocket