vue2 + websocket 断线重连 + 实时数据

发布时间 2023-10-17 09:30:54作者: persist_in

一、websocket事件

  -1 打开事件

    Socket.onopen 连接建立时触发

  -2 消息事件

    Socket.onmessage 客户端接收服务端数据时触发

  -3 错误事件

    Socket.onerror 通信发生错误时触发

  -4 关闭事件

    Socket.onclose 连接关闭时触发

二、websocket方法

  -1 发送数据(注 - 只有在连接打开时才可以发送消息。

    Socket.send() 使用连接发送数据

  -2 关闭连接

    Socket.close() 关闭连接  【代表握手再见,它完全终止连接,在重新建立连接之前不能传输任何数据。】

 

三、实现websocket 断线重连 和 实时更新数据

 // 创建
    wsConnect() {
      /**
       * 重连时这里要重新将实例交给ws
       * 1.发布订阅监听
       * 2.直接传
       */
   
     var lockReconnect = false; //避免ws重复连接
      var ws = null; // 判断当前浏览器是否支持WebSocket
      var wsUrl = `ws://192.168.0.33:8686/ws?uid=${this.userId}`;  //后端的ws接口
      createWebSocket(wsUrl); //连接ws

      function createWebSocket(url =  `ws://192.168.0.33:8686/ws?uid=${this.userId}`) {
        try {
          if ("WebSocket" in window) {
            ws = new WebSocket(url);
          }
          initEventHandle();
        } catch (e) {
          reconnect(url);
          console.log(11, e);
        }
      }

      const self = this;
      function initEventHandle() {
        ws.onclose = function (msg) {
          reconnect(wsUrl);
          console.log("llws连接关闭!" + new Date().toLocaleString());
        };
        ws.onerror = function (msg) {
          reconnect(wsUrl);
        };
        ws.onopen = function (msg) {
          heartCheck.reset().start(); //心跳检测重置
          console.log("llws连接成功!" + new Date().toLocaleString());
        };
        ws.onmessage = (msg) => {
          //如果获取到消息,心跳检测重置
          heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
          let data = JSON.parse(msg.data);
          console.log(22,data);
          // 变动值 (注意this指向)
          self.newnumber=data.countScore
          self.push=data
          // self.leaderboard.sort((a, b) => b.countScore - a.countScore);
        };

        // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function (msg) {
          console.log("222", msg);
          ws.close();
        };

        function reconnect(url) {
          if (lockReconnect) return;
          lockReconnect = true;
          setTimeout(function () {
            //没连接上会一直重连,设置延迟避免请求过多
            createWebSocket(url);
            lockReconnect = false;
          }, 2000);
        }

        //心跳检测
        var heartCheck = {
          timeout: 2000, //2000发一次心跳
          timeoutObj: null,
          serverTimeoutObj: null,
          reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
          },
          start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
              //这里发送一个心跳,后端收到后,返回一个心跳消息,
              //onmessage拿到返回的心跳就说明连接正常
              ws.send("ping");
              console.log("ping!");

              // self.serverTimeoutObj = setTimeout(function () {
              //   //如果超过一定时重置间还没,说明后端主动断开了
              //   ws.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
              // }, self.timeout);
            }, this.timeout);
          },
        };
      }
    },

this.wsConnect()  //调用

  

注:该文档为个人理解所写,有误可建议修改