【筆記】vue中websocket心跳機制

data () {
      return {
        ws: null,//創建的鏈接
        lockReconnect: false,//是否真正創建鏈接
        timeout: 28*1000,//30秒一次心跳
        timeoutObj: null,//心跳心跳倒計時
        serverTimeoutObj: null,//心跳倒計時
        timeoutnum: null,//斷開 重連倒計時
      }
    },
    created() {
      this.initWebpack();
    },  
    methods: {
      initWebpack(){
        this.ws = new WebSocket(process.env.SOCKET_OTC);
        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(){//開啓心跳
        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() {
        var msg = JSON.stringify({cmd: 'enter_chatting', token:this.COOKIE.getCookie("token")});
        this.ws.send(msg);
        console.log("open");
        this.getNoReadRecords();
        //開啓心跳
        this.start();
      },
      onmessage(e) {
        this.mydata = JSON.parse(e.data);
        if(this.mydata.fromID == this.states.customerId){
          this.mydata.chatType = 2;
        }else{
          this.mydata.chatType = 1;
        }
        var content =this.getContentTypes(this.mydata.content,this.mydata.chatType);
        this.records.push(this.mydata);
        //收到服務器信息,心跳重置
        this.reset();
      },
      onclose(e) {
        console.log("鏈接關閉");
        console.log('websocket 斷開: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
        var msg = JSON.stringify({cmd: 'out_chatting', token:this.COOKIE.getCookie("token")});
        this.ws.send(msg);
        //重連
        this.reconnect();
      },
      onerror(e) {
        console.log("出現錯誤");
        //重連
        this.reconnect();
      }
}
相關文章
相關標籤/搜索