Vue中WebSocket链接中断、心跳机制防止自动断开

1、WebSocket链接中断原因
WebSocket断开的原因有很多,最好在WebSocket断开时,将错误打印出来。

      const Wsurl = `${process.env.VUE_APP_WEBSOCKET_BASE_URL}/${sessionStorage.getItem('userId')}`
      this.ws = new WebSocket(Wsurl);
      this.ws.onclose = function (e) {
			console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
      };

在这里插入图片描述
二、心跳机制防止自动断开
WebSocket在一段时间内没有进行通讯便会自读断开链接,可以每隔30秒或一分钟向服务器发送一次通讯防止链接终端

  data() {
    return {
          lockReconnect: false,
          ws: null,
    }
 },
methods: {
  join() {
      const Wsurl = `后端WebSocket接口URl`
      this.ws = new WebSocket(Wsurl);
      const self = this;
      this.ws.onopen = function (event) {
        console.log('已经打开连接');
        //心跳检测重置
        self.heartCheckReset()
        self.heartCheckStart()
        self.text_content = self.text_content + "已经打开连接!" + "\n";
      };
        this.ws.onmessage = function (event) {
        self.heartCheckReset()
        self.heartCheckStart()
        self.text_content = event.data + "\n";
        if (event.data == 'ping' || event.data == '连接成功') return ''
        console.log(event);
        self.getNoticeList()
      };
        this.ws.onclose = function (event) {
        console.log('关闭');
        console.log(event, '关闭');
        self.reconnect()
        self.text_content = self.text_content + "已经关闭连接!" + "\n";
      };
}//若链接中断30秒后创建新的链接
    reconnect() {
      if (this.lockReconnect) return ''
      this.lockReconnect = true
      setTimeout(() => {
        this.join()
        this.lockReconnect = false
        //若链接中断30秒后创建新的链接
      }, 30000)
    },
    //清空定时器
	heartCheckReset() {
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
    },
        // 开启定时器
    heartCheckStart() {
      var self = this;
      this.timeoutObj = setTimeout(function () {
        //这里发送一个心跳,后端收到后,返回一个心跳消息,
        //onmessage拿到返回的心跳就说明连接正常
        self.ws.send("ping");
        console.log("ping!")
        self.serverTimeoutObj = setTimeout(function () { //如果超过一定时间还没重置,说明后端主动断开了
          self.ws.close();
        },30000 )
      }, 30000)

    },
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值