WebSocket心跳机制

data(){
  return{
        // websocket
        ws: {},
        wsUrl: 'wss://jhsy.linkcloud360.com/ws',
        heart_jump: false, //websocket 心跳状态
        ws_heart: '', // ws心跳定时器
        //websocket持续连接的定时器
        continuous_link: null,
  }
}
  created() {
    // //页面刚进入时开启长连接
    this.creat_socket(this.wsUrl);
  },
  destroyed() {

  },
  methods: {
     // WebSjocket操作
      creat_socket(url) {
        this.ws = new WebSocket(url);
        this.close_heart();
        this.initWebSocket();
      },
      initWebSocket() {
        let that = this;
        let ws = that.ws;
        // 打开WebSjocket
        ws.onopen = function (e) {
          console.log("WebSjocket已经打开");
          that.heart_jump = true; // 心跳状态打开
          that.heart();

          // 再次清除防止重复请求
          clearInterval(that.continuous_link);
        };

        // 接收WebSjocket
        // let mouse_over = [];
        ws.onmessage = function (event) {
          console.log("接收WebSjocket", event);

          if ((!event && !event.data) || event.data == "undefined") {
            return;
          } else {
  			let data = event.data
          }
        }
        // 关闭
        ws.onclose = function (e) {
          if (that.heart_jump) {
            that.close_heart();
            that.heart_jump = false;

          }
          console.log("WebSocket关闭");
        };

        // WebSocket发生错误
        ws.onerror = function (e) {
          if (that.heart_jump) {
            that.close_heart();
            that.heart_jump = false;
          }
          that.reconnect(that.wsUrl);
          console.log("WebSocket发生错误");
        };
      },

      heart(props) {
        let that = this;
        this.ws_heart = setInterval(() => {
          that.ws.send(props);
        }, 10 * 1000);
      },

      close_heart() {
        console.log("ws心跳结束");
        clearInterval(this.ws_heart);
        this.ws_heart = null;
      },

      reconnect(url) {
        if (this.lockReconnect) return;
        this.lockReconnect = true;
        let that = this;
        // 先清除定时器
        clearInterval(this.continuous_link);

        this.continuous_link = setInterval(function () {
          //没连接上会一直重连,设置延迟避免请求过多
          that.lockReconnect = false;
          that.creat_socket(url);
          console.log("重启中...");
        }, 5000);
      },
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值