美文网首页
webstock的心跳包实现

webstock的心跳包实现

作者: Young_Kind | 来源:发表于2018-05-22 15:58 被阅读173次
          let webstockUrl='ws://192.168.1.119:8001';
          let WebSocketObj=null;
          var lockReconnect = false;//避免重复连接
          var tt;
          function createWebSocket() {
            try {
              WebSocketObj= new WebSocket(webstockUrl);
              console.log('初始化');
              init();
            } catch(e) {
              console.log(e);
              console.log('catch');
              reconnect(webstockUrl);
            }
          }
          function init() {
            WebSocketObj.onclose = function () {
              console.log('链接关闭');
              reconnect(webstockUrl);
            };
            WebSocketObj.onerror = function() {
              console.log('发生异常了');
              reconnect(webstockUrl);
            };
            WebSocketObj.onopen = function () {
              //心跳检测重置
              heartCheck.start();
            };
            WebSocketObj.onmessage = function (event) {
              //拿到任何消息都说明当前连接是正常的
              heartCheck.start();
            }
          }
    
          /**
           * 尝试重连
           * @param url
           */
          function reconnect(url) {
            console.log('尝试重连',lockReconnect);
            if(lockReconnect) {
              return;
            };
            lockReconnect = true;
            //没连接上会一直重连,设置延迟避免请求过多
            tt && clearTimeout(tt);
            tt = setTimeout(function () {
              createWebSocket(url);
              lockReconnect = false;
            }, 5000);
          }
          //心跳检测
          var heartCheck = {
            timeout: 5000,
            timeoutObj: null,
            serverTimeoutObj: null,
            start: function(){
             // console.log('start');
              var self = this;
              this.timeoutObj && clearTimeout(this.timeoutObj);
              this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
              this.timeoutObj = setTimeout(function(){
                //这里发送一个心跳,后端收到后,返回一个心跳消息,
                WebSocketObj.send("ping");
                self.serverTimeoutObj = setTimeout(function() {
                  console.log('');
                  WebSocketObj.close();
                }, self.timeout);
    
              }, this.timeout)
            }
          }
          createWebSocket(webstockUrl);
    
          export const $webstock =WebSocketObj
    
    

    相关文章

      网友评论

          本文标题:webstock的心跳包实现

          本文链接:https://www.haomeiwen.com/subject/litkjftx.html