52ky 发表于 2023-1-8 10:29:02

Vue中使用WebSocket(含心跳)(uniapp或者vue html)可用

data(){
return{
      websock: null, //建立的连接
      lockReconnect: false, //是否真正建立连接
      timeout: 20 * 1000, //20秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null //断开 重连倒计时
}
}
created() {
    // //页面刚进入时开启长连接
    this.initWebSocket();
},
destroyed() {
    //页面销毁时关闭长连接
    this.websocketclose();
},
methods: {
   initWebSocket() {
      //建立连接
      //初始化weosocket
      const wsuri = "ws://localhost:9998/echo";
      //建立连接
      this.websock = new WebSocket(wsuri);
      //连接成功
      this.websock.onopen = this.websocketonopen;
      //连接错误
      this.websock.onerror = this.websocketonerror;
      //接收信息
      this.websock.onmessage = this.websocketonmessage;
      //连接关闭
      this.websock.onclose = this.websocketclose;
    },
    reconnect() {
      //重新连接
      var that = this;
      if (that.lockReconnect) {
      return;
      }
      that.lockReconnect = true;
      //没连接上会一直重连,设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function() {
      //新连接
      that.initWebSocket();
      that.lockReconnect = false;
      }, 5000);
    },
    reset() {
      //重置心跳
      var that = this;
      //清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重启心跳
      that.start();
    },
    start() {
      //开启心跳
      var self = this;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setTimeout(function() {
      //这里发送一个心跳,后端收到后,返回一个心跳消息
      if (self.websock.readyState == 1) {
          //如果连接正常
          self.websock.send("heartbeat");
      } else {
          //否则重连
          self.reconnect();
      }
      self.serverTimeoutObj = setTimeout(function() {
          //超时关闭
          self.websock.close();
      }, self.timeout);
      }, self.timeout);
    },
    websocketonopen() {
      //连接成功事件
      this.websocketsend('发送数据');
      //提示成功
      console.log("连接成功", 3);
      //开启心跳
      this.start();
    },
    websocketonerror(e) {
      //连接失败事件
      //错误
      console.log("WebSocket连接发生错误");
      //重连
      this.reconnect();
    },
    websocketclose(e) {
      //连接关闭事件
      //提示关闭
      console.log("连接已关闭");
      //重连
      this.reconnect();
    },
    websocketonmessage(event) {
      //接收服务器推送的信息
      //打印收到服务器的内容
      console.log("收到服务器信息",event.data);
      let data=event.data
      //收到服务器信息,心跳重置
      this.reset();
    },
    websocketsend(msg) {
      //向服务器发送信息
      this.websock.send(msg);
    }
}




vue 中使用websocket,结合vuex实现实时监听:

(data(){
return {
      websock: null, //established connection
      lockReconnect: false, //whether the connection is actually established
      timeout: 20 * 1000, //1 heartbeat every 20 seconds
      timeoutObj: null, //heartbeat heartbeat countdown
      serverTimeoutObj: null, //heartbeat countdown
      timeoutnum: null //Disconnect and reconnect countdown
}
}
created() {
    // //Enable long connection when the page just entered
    this.initWebSocket();
},
destroyed() {
    //Close the long connection when the page is destroyed
    this. websocket close();
},
methods: {
   initWebSocket() {
      //establish connection
      //Initialize weosocket
      const wsuri = "ws://localhost:9998/echo";
      //establish connection
      this.websock = new WebSocket(wsuri);
      //connection succeeded
      this.websock.onopen = this.websocketonopen;
      //error in connecting
      this.websock.onerror = this.websocketonerror;
      //Receive information
      this.websock.onmessage = this.websocketonmessage;
      //connection closed
      this.websock.onclose = this.websocketclose;
    },
    reconnect() {
      //reconnect
      var that = this;
      if (that. lockReconnect) {
      return;
      }
      that. lockReconnect = true;
      //If you are not connected, you will always reconnect, set a delay to avoid too many requests
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function() {
      //new connection
      that.initWebSocket();
      that. lockReconnect = false;
      }, 5000);
    },
    reset() {
      //reset heartbeat
      var that = this;
      //clear time
      clearTimeout(that. timeoutObj);
      clearTimeout(that. serverTimeoutObj);
      //restart heartbeat
      that. start();
    },
    start() {
      //Enable heartbeat
      var self = this;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self. timeoutObj = setTimeout(function() {
      //Send a heartbeat here, and the backend will return a heartbeat message after receiving it
      if (self. websock. readyState == 1) {
          //if the connection is ok
          self.websock.send("heartbeat");
      } else {
          //Otherwise reconnect
          self. reconnect();
      }
      self. serverTimeoutObj = setTimeout(function() {
          //timeout close
          self. websock. close();
      }, self. timeout);
      }, self. timeout);
    },
    websocketonopen() {
      //connection success event
      this.websocketsend('send data');
      //prompt success
      console.log("connected successfully", 3);
      //Enable heartbeat
      this. start();
    },
    websocketonerror(e) {
      //Connection failure event
      //mistake
      console.log("WebSocket connection error occurred");
      //Reconnection
      this. reconnect();
    },
    websocketclose(e) {
      //connection close event
      //prompt close
      console.log("The connection is closed");
      //Reconnection
      this. reconnect();
    },
    websocketonmessage(event) {
      //Receive the information pushed by the server
      //Print the content received from the server
      console.log("Received server information", event.data);
      let data=event.data
      //Receive server information, heartbeat reset
      this. reset();
    },
    websocketsend(msg) {
      //Send information to the server
      this.websock.send(msg);
    }
}




Use websocket in vue, combined with vuex to realize real-time monitoring:)



页: [1]
查看完整版本: Vue中使用WebSocket(含心跳)(uniapp或者vue html)可用