websocket 心跳包(此方法也是借鉴网上,并非原创但实测没问题)

data() {
    return {
      ws: null, //建立的连接
      lockReconnect: false, //是否真正建立连接
      timeout: 60 * 1000, //60秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时

    }
}

methods:{
// 连接ws
    initWebpack() {
      let token = this.$store.state.mUinfo.id
      let wsurl = ''; //ws地址,这里加入自己的地址即可
      wsurl = 'ws://' + xxxxx + 'api/v1/users/notices/ws'
      this.ws = new WebSocket(wsurl, [token]);
      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) {
      let data = JSON.parse(e.data);
      // console.log('接收消息', data);
      //收到服务器信息,心跳重置
      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);
    },
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值