websocket心跳连接

    initWebSocket() {
      this.destroyWebSocket()
      const wsUrl = "ws://" + window.location.host + "/webSocket"
      this.websock = new WebSocket(wsUrl)
      //连接成功
      this.websock.onopen = this.websocketonopen;
      //接收信息
      this.websock.onmessage = this.websocketonmessage;
      //连接错误
      this.websock.onerror = this.websocketonerror;
      //连接关闭
      this.websock.onclose = this.websocketclose;
    },
    // 开启心跳
    startHeartbeat() {
      console.log('startHeartbeat===>', this.websock);
      this.heartbeatTiming && clearTimeout(this.heartbeatTiming)
      this.heartbeatCountdown && clearTimeout(this.heartbeatCountdown)
      this.heartbeatTiming = setTimeout(() => {
        if (this.websock && this.websock.readyState === 3) return
        // 发送心跳
        this.websock && this.websock.send(JSON.stringify({
          "userId": getUserToken() ? JSON.parse(getUserToken()).id : null,
          "msg": "HeartbeatPacket"
        }))
        console.log('开启心跳~~~~~~~~~');
        this.heartbeatCountdown = setTimeout(() => {
          this.websock && this.websock.close();
        }, this.timeout)
      }, this.timeout)
    },
    // 重置心跳
    resetHeartbeat() {
      console.log('重置心跳~~~~~~~~~~');
      clearTimeout(this.heartbeatTiming);
      clearTimeout(this.heartbeatCountdown);
      this.startHeartbeat()
    },
    // 重新连接
    reconnect() {
      console.log('重新连接~~~~~~~~~~!!!!!!!!');
      console.log('this.isConcat===>', this.isConcat);
      if (this.isConcat) return;
      this.isConcat = true;
      //没连接上会一直重连,设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum)
      this.timeoutnum = setTimeout(() => {
        this.initWebSocket();
        this.isConcat = false
      }, 5000)
    },
    //连接成功事件
    websocketonopen() {
      console.log('连接成功~~~~~~~~~~');
      if (this.websock && this.websock.readyState === 1) {
        this.websock.send(JSON.stringify({
          "userId": getUserToken() ? JSON.parse(getUserToken()).id : null,
          "msg": "read"
        }))
        this.startHeartbeat()
      }
    },
    //连接失败事件
    websocketonerror() {
      console.log('发生异常~~~~~~~~~~');
      // 重新连接
      this.reconnect()
    },
    //接收服务器推送的信息
    websocketonmessage(e) {
      console.log("接收服务器推送的信息~~~~~~~~~~", e.data);
      try {
        if (e.data === "HEADERBEAT") {
          console.log('收到心跳~~~~');
          this.startHeartbeat()
        }
        if (e.data) {
          console.log('获取值!~~~~~~~~~', e.data);
        }
      } catch (error) {
        console.warn(error);
      }
    },
    //连接关闭事件
    websocketclose() {
      if (this.$router.currentRoute.name == "deviceData") {
        console.log('断线重连~~~~~~~~~~');
        //重连
        this.reconnect();
      } else {
        this.websock.close()
        this.websock = null
      }
    },
    // 向服务发送信息
    websocketsend() {
      console.log('向服务发送信息~~~~~~~~~~');
      this.websock.send(JSON.stringify({
        "userId": getUserToken() ? JSON.parse(getUserToken()).id : null,
        "msg": "idleClose"
      }))
    },
    destroyWebSocket() {
      if (this.websock) {
        console.log('this.websock.readyState====>',);
        if (this.$router.currentRoute.name !== "deviceData") {
          this.websocketsend()
          this.websock.close()
        } else {
          this.websock.close()
        }
        console.log('离开网页,关闭websock~~~~~~~~~~');
      }
    }
  destroyed() {
    this.destroyWebSocket()
  },
  mounted() {
    this.initWebSocket()
    console.log('mounted~~~~~');
  },
  data() {
    return {
      websock: null,//建立的连接
      lockReconnect: false,//是否真正建立连接
      isConcat: false,//是否真正建立连接
      timeout: 30 * 1000,//30秒一次心跳
      heartbeatTiming: null,//心跳心跳倒计时
      heartbeatCountdown: null,//心跳倒计时  
      timeoutnum: null,//断开 重连倒计时
    };
  },
posted @ 2022-01-12 15:03  云霄紫潭  阅读(256)  评论(0编辑  收藏  举报