zoukankan      html  css  js  c++  java
  • vue 中使用 webSocket 收发数据, 增加 " 心跳机制 " 保持连接.

     1、页面加载时候,开启长连接:

     created() {
        this.adminIds = getadminId();
        this.tokens = getToken();
        this.merIds = getmerId();
        //页面刚进入时,判断有无token,有则开启长连接
        if(this.tokens) {
          this.initWebSocket();
        } else {}
    
      },
    

     2、页面销毁、关闭长连接:

    destroyed: function() {
        //页面销毁时关闭长连接
        this.websocketclose();
      },
    

     3、定义长连接:

        initWebSocket(){ //初始化weosocket
          const that = this;
          const wsuri = 'wss:// + 域名 + /merchantWebSocket?' + 'adminId=' + this.adminIds + '&token=' + this.tokens + '&userId=' + this.merIds;   //ws地址,这个要跟后端协商定义
          // console.log(wsuri);
          //建立连接
          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;
        },
    

     4、断线重连:

    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);
        },
    

     5、其他连接方式:

    websocketonopen() {//连接成功事件
          console.log("WebSocket连接成功");
          //开启心跳
          this.start();
        },
        websocketonerror(e) {//连接失败事件
          //错误
          console.log("WebSocket连接发生错误");
          //重连
          this.reconnect();
        },
        websocketclose(e) {//连接关闭事件
          //关闭
          console.log("WebSocket关闭");
          // console.log("connection closed (" + e.code + ")");
          //重连
          this.reconnect();
        },
        websockOpen() {//打开连接
          console.log("WebSocket连接成功");
          this.start();
        },
    websocketonmessage(e){ //数据接收
    console.log(e.data);
    //收到服务器信息,心跳重置
    // this.reset();
    },

         6、开启心跳:

    start(){
          // console.log('开启心跳');
          const self = this;
          let _num = 3;
          self.timeoutObj && clearTimeout(self.timeoutObj);
          self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
          self.timeoutObj = setTimeout(function(){
            //这里发送一个心跳,后端收到后,返回一个心跳消息,
            if (self.websock.readyState === 1) {//如果连接正常
              // console.log(self.websock);
              self.websock.send("heartCheck");
            }else{//否则重连
              self.reconnect();
            }
            self.serverTimeoutObj = setTimeout(function() {
              //超时关闭
              _num--;
              //计算答复的超时次数
              if(_num === 0) {
                self.websocketclose();
              }
            }, self.timeout);
    
          }, self.timeout)
        },

        7、重置心跳:

    reset(){
          // console.log('重置心跳');
          var that = this;
          //清除时间
          clearTimeout(that.timeoutObj);
          clearTimeout(that.serverTimeoutObj);
          //重启心跳
          that.start();
        },
    

     8、export default ,data 中定义:

    data() {
        return {
          levelList: null,
          adminIds: '',
          tokens: '',
          merIds: '',
          webSocket: null,
          lockReconnect: false,//是否真正建立连接
          timeout: 28*1000,//30秒一次心跳
          timeoutObj: null,//心跳心跳倒计时
          serverTimeoutObj: null,//心跳倒计时
          timeoutnum: null,//断开 重连倒计时
        }
      },
    

      

  • 相关阅读:
    mysql配置utf8_mb4
    Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by serv
    MongoDB自动删除过期数据--TTL索引
    正则小公举
    苹果手机弹起输入框将页面上的元素上移
    location的部分属性
    在ajax请求下的缓存机制
    苹果机的时间格式转换为时间搓
    $.extendGit 丢弃所有本地修改的方法
    调起微信扫一扫
  • 原文地址:https://www.cnblogs.com/moguzi12345/p/13389284.html
Copyright © 2011-2022 走看看