快捷搜索: 王者荣耀 脱发

前端webSocket初始化,心跳检测代码块

class WSocket {
          
   
    ws=null;
    timeout=20000;
    timeoutObj= null;
    serverTimeoutObj=null;
    init () {
          
   
      this.ws = new WebSocket(baseUrl);
      this.ws.addEventListener(open, () => {
          
   
        this.reset().start(); // 心跳检测
      });
      this.ws.addEventListener(close, () => {
          
   
        this.reconnect();
      });
      this.ws.addEventListener(error, () => {
          
   
        this.reconnect();
      });
      this.ws.addEventListener(message, (data) => {
          
   
        this.ws.reset().start();
        store.commit(changeSocketMessage, data); // 分发data
      });
    }
    reconnect (url) {
          
   
      setTimeout(function () {
          
    // 没连接上会一直重连,设置延迟避免请求过
        this.init();
      }, 2000);
    }
    reset () {
          
   
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      return this;
    }
    start () {
          
   
      const self = this;
      this.timeoutObj = setTimeout(function () {
          
   
        // 这里发送一个心跳,后端收到后,返回一个心跳消息,
        // onmessage拿到返回的心跳就说明连接正常
        self.ws.send(JSON.stringify({
          
    type: 3, msg: HeartBeat + new Date() }));
        self.serverTimeoutObj = setTimeout(function () {
          
    // 如果超过一定时间还没重置,说明后端主动断开了
          self.ws.close();// 如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
        }, self.timeout);
      }, self.timeout);
    }
  }
// 使用
  const $ws = new WSocket();
  $ws.init();
经验分享 程序员 微信小程序 职场和发展