Vue+WebSocket 心跳機制 保持連接


<template>
  <div></div>
</template>
<script>
export default {
  data() {
    return {
      // websocket
      websock: null, //建立的連接
      lockReconnect: false, //是否真正建立連接
      timeout: 28 * 1000, //30秒一次心跳
      timeoutObj: null, //心跳心跳倒計時
      serverTimeoutObj: null, //心跳倒計時
      timeoutnum: null, //斷開 重連倒計時
    }
  },
  created() {
    //頁面剛進入時開啟長連接
    this.initWebSocket();
  },
  destroyed: function () {
    //頁面銷毀時關閉長連接
    this.websocketclose();
  },
  methods: {
    // WebSocket
    //建立連接
    initWebSocket() {
      //初始化weosocket
      //const wsuri = "ws://sms.填寫您的地址.com/websocket/" + this.charId; //ws地址
      const wsuri ="ws://sms.balabala.com/websocket/" + this.$route.query.telphone
      //建立連接
      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(
            '{"toUserId":"' + self.$route.query.telphone + '"}'
          );
          console.log("發送消息");
        } else {
          //否則重連
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function () {
          //超時關閉
          self.websock.close();
        }, self.timeout);
      }, self.timeout);
    },
    //連接成功事件
    websocketonopen() {
      //提示成功
      console.log("連接成功", 3);
      //開啟心跳
      this.start();
    },
    //連接失敗事件
    websocketonerror(e) {
      //錯誤
      console.log("WebSocket連接發生錯誤");
      //錯誤提示
      console.log("Websocket error, Check you internet!");
      //重連
      this.reconnect();
    },
    //連接關閉事件
    websocketclose(e) {
      //關閉
      console.log("connection closed (" + e + ")");
      //提示關閉
      console.log("連接已關閉", 3);
      //重連
      this.reconnect();
    },
    //接收服務器推送的信息
    websocketonmessage(event) {
      //打印收到服務器的內容
      //數據接收
      let that = this;
      const redata = JSON.parse(event.data);
      console.log(redata,"數據接收");
      //收到服務器信息,心跳重置
      this.reset();
    },
    //向服務器發送信息
    websocketsend(msg) {
      //數據發送
      this.websock.send(msg);
    },
  },
};
</script>
<style  scoped>

</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM