• Vue中WebSocket加入心跳机制


    <script>
    import { collectService } from '@/services';
    
    export default {
      prop: ['formWhere'],
      data() {
        return {
          dialogPop: false,
          isDisabled: true,
          webInfo: [],
          id: null,
          ws: null,//建立的连接
          lockReconnect: false,//是否真正建立连接
          timeout: 58*1000,//58秒一次心跳
          timeoutObj: null,//心跳心跳倒计时
          serverTimeoutObj: null,//心跳倒计时
          timeoutnum: null,//断开 重连倒计时
        }
      },
      created() {
        this.initWebpack();
      },
      methods: {
        initWebpack(){
          const wsurl='wss://XXXXXXX';//ws地址,这里加入自己的地址即可
          this.ws = new WebSocket(wsurl);
          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) {
          console.log('接收信息', e);
          console.log('接收信息', e.data);
          //下面这块代码,接收到后端返回的消息后,根据自己的需求去判断
          if(e.data == 'heartCheck'){
            // this.webInfo = '';
          }else {
            let data = JSON.parse(e.data);
            if(data && data.length > 0){
              let arr = [];
              data.forEach(element => {
                if(element.collectorId == localStorage.getItem('id')) {
                  arr.push(element);
                  return;
                }
              });
              this.webInfo = arr;
              console.log('this.webInfo--',this.webInfo);
            }
          }
          //收到服务器信息,心跳重置
          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);
        },
      },
    }
    </script>
    

    这是本人最终用到的代码,新测真实有效

    参考这篇文章

    https://blog.csdn.net/kang19980516/article/details/104658081?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduend~default-1-104658081.nonecase&utm_term=vue%E4%B8%AD%20websocket%E5%BF%83%E8%B7%B3%E6%9C%BA%E5%88%B6&spm=1000.2123.3001.4430

  • 相关阅读:
    一千亿亿亿字节
    分布式发布订阅消息系统
    Google Chrome 的内核引擎 WebKit 介绍
    找项目网站C# 下写入视频的简单实现
    学ios开发:Delegate,Action Sheet, Alert
    Web服务器
    Google Chrome Source Code 源码下载
    大数据处理的趋势五种开源技术介绍
    MDA项目思路小结
    重新发布本人所有博客文章中涉及的代码与工具(大部分是C++和Java)
  • 原文地址:https://www.cnblogs.com/tanweiwei/p/13969132.html
Copyright © 2020-2023  润新知