1. 程式人生 > 實用技巧 >Vue中WebSocket加入心跳機制

Vue中WebSocket加入心跳機制

<script>
import { collectService } from '@/services';

export default {
  prop: ['formWhere'],
  data() {
    return {
      dialogPop: false,
      isDisabled: true,
      webInfo: [],
      id: null,
      ws: null,//建立的連線
      lockReconnect: false,//是否真正建立連線
      timeout: 58*1000,//58秒一次心跳
      timeoutObj: null,//心跳心跳倒計時
      serverTimeoutObj: null,//心跳倒計時
      timeoutnum: null,//斷開 重連倒計時
    }
  },
  created() {
    this.initWebpack();
  },
  methods: {
    initWebpack(){
      const wsurl='wss://XXXXXXX';//ws地址,這裡加入自己的地址即可
      this.ws = new WebSocket(wsurl);
      this.ws.onopen = this.onopen;
      this.ws.onmessage = this.onmessage;
      this.ws.onclose = this.onclose;
      this.ws.onerror = this.onerror;
    },
    reconnect() {//重新連線
      var that = this;
      if(that.lockReconnect) {
        return;
      };
      that.lockReconnect = true;
      //沒連線上會一直重連,設定延遲避免請求過多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function () {
        //新連線
        that.initWebpack();
        that.lockReconnect = false;
      },5000);
    },
    reset(){//重置心跳
      var that = this;
      //清除時間
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重啟心跳
      that.start();
    },
    start(){ //開啟心跳
      console.log('開啟心跳');
      var self = this;
      self.timeoutObj && clearTimeout(self.timeoutObj);
      self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
      self.timeoutObj = setTimeout(function(){
        //這裡傳送一個心跳,後端收到後,返回一個心跳訊息,
        if (self.ws.readyState == 1) {//如果連線正常
          self.ws.send("heartCheck"); //這裡可以自己跟後端約定
        }else{//否則重連
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function() {
          //超時關閉
          self.ws.close();
        }, self.timeout);
      }, self.timeout)
    }, 
   onopen() {
      console.log("open");
      //開啟心跳
      this.start();
    },
    onmessage(e) {
      console.log('接收資訊', e);
      console.log('接收資訊', e.data);
      //下面這塊程式碼,接收到後端返回的訊息後,根據自己的需求去判斷
      if(e.data == 'heartCheck'){
        // this.webInfo = '';
      }else {
        let data = JSON.parse(e.data);
        if(data && data.length > 0){
          let arr = [];
          data.forEach(element => {
            if(element.collectorId == localStorage.getItem('id')) {
              arr.push(element);
              return;
            }
          });
          this.webInfo = arr;
          console.log('this.webInfo--',this.webInfo);
        }
      }
      //收到伺服器資訊,心跳重置
      this.reset();
    },
    onclose(e) {
      console.log("連線關閉");
      console.log('websocket 斷開: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
      //重連
      this.reconnect();
    },
    onerror(e) {
      console.log("出現錯誤");
      //重連
      this.reconnect();
    },
    onsend(msg) {//向伺服器傳送資訊
      //資料傳送
      this.websock.send(msg);
    },
  },
}
</script>

這是本人最終用到的程式碼,新測真實有效

參考這篇文章

https://blog.csdn.net/kang19980516/article/details/104658081?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduend~default-1-104658081.nonecase&utm_term=vue%E4%B8%AD%20websocket%E5%BF%83%E8%B7%B3%E6%9C%BA%E5%88%B6&spm=1000.2123.3001.4430