webSocket心跳机制(vue)

首先在连接成功的回调里就开始发送心跳机制

    // 连接成功建立的回调
    onopenCallback: function (event) {
      console.log("WebSocket:已连接");
      // 心跳检测重置
      this.heartCheck.reset().start();
    },

当接收到服务器返回的心跳包时,说明连接正常,心跳检测重置,那么会清除外层定时器,这就意味着里层定时器根本不会执行,也就不用重连或执行其他操作
如果没有正常返回,外层定时器就不会被清除,里层定时器就会执行,可能会执行重连或其他操作

    // 接收到消息的回调
    getMessageCallback: function (msg) {
      console.log(msg);
      // console.log(msg.data);
      if (msg.data.indexOf("HeartBeat") > -1) {
        // 心跳回复——心跳检测重置
        // 收到心跳检测回复就说明连接正常
        console.log("收到心跳检测回复");
        // 心跳检测重置
        this.heartCheck.reset().start();
      } else {
        if (msg.data == "连接成功") {
          return
        }
        let data = JSON.parse(msg.data);
        this.messages.push(data.message);
        // 普通推送——正常处理
        console.log("收到推送消息");
        // 相关处理
      }
    },

完整代码:

<template>
  <div>
    <h1>这是 {{ id }}</h1>
    <ul>
      <li v-for="message in messages" :key="message.id">
        {{ message }}
      </li>
    </ul>
    <input type="text" placeholder="对方ID" v-model="toId">
    <input v-model="inputMessage" type="text" @keyup.enter="sendMessage">
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: localStorage.getItem('id'),
      toId: "",
      messages: [],
      inputMessage: '',

      // websocket相关
      socketObj: "", // websocket实例对象a
      //心跳检测
      heartCheck: {
        vueThis: this, // vue实例
        timeout: 10000, // 超时时间
        timeoutObj: null, // 计时器对象——向后端发送心跳检测
        serverTimeoutObj: null, // 计时器对象——等待后端心跳检测的回复
        // 心跳检测重置
        reset: function () {
          clearTimeout(this.timeoutObj);
          clearTimeout(this.serverTimeoutObj);
          return this;
        },
        // 心跳检测启动
        start: function () {
          this.timeoutObj && clearTimeout(this.timeoutObj);
          this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);

          this.timeoutObj = setTimeout(() => {
            // 这里向后端发送一个心跳检测,后端收到后,会返回一个心跳回复
            this.vueThis.socketObj.send("HeartBeat");

            console.log("发送心跳检测");

            this.serverTimeoutObj = setTimeout(() => {
              // 如果超过一定时间还没重置计时器,说明websocket与后端断开了
              console.log("未收到心跳检测回复");
              // 关闭WebSocket
              this.vueThis.socketObj.close();
            }, this.timeout);
            
          }, this.timeout);
          
        },
      },
      socketReconnectTimer: null, // 计时器对象——重连
      socketReconnectLock: false, // WebSocket重连的锁
      socketLeaveFlag: false, // 离开标记(解决 退出登录再登录 时出现的 多次相同推送 问题,出现的本质是多次建立了WebSocket连接)
    };
  },
  created() {
    // const WebSocket = window.WebSocket
    // this.ws = new WebSocket(`ws://localhost:7000/ws?fromId=${this.id}`);
    console.log("离开标记", this.socketLeaveFlag);
  },
  mounted() {
    // websocket启动
    this.createWebSocket();
  },
  destroyed() {
    // 离开标记
    this.socketLeaveFlag = true;
    // 关闭WebSocket
    this.socketObj.close();
  },
  methods: {
    sendMessage() {
      if (!this.inputMessage) {
        return;
      }
      this.socketObj.send(JSON.stringify({ message: this.inputMessage, fromId: this.id, toId: this.toId }));
      this.inputMessage = '';
    },

    // websocket启动
    createWebSocket() {
      let webSocketLink = `ws://localhost:7000/ws?fromId=${this.id}`; // webSocket地址
      try {
        if ("WebSocket" in window) {
          this.socketObj = new WebSocket(webSocketLink);
        } else if ("MozWebSocket" in window) {
          this.socketObj = new MozWebSocket(webSocketLink);
        }
        // websocket事件绑定
        this.socketEventBind();
      } catch (e) {
        console.log("catch" + e);
        // websocket重连
        this.socketReconnect();
      }
    },
    // 先说ws实例化过程
    // 说明try和catch -> 简单带一下重连
    // 回归成功状态 -> ws的正常的流程(可以从代码角度)
    // 根据用户浏览页面导致ws断开,引出心跳机制

    // websocket事件绑定
    socketEventBind() {
      // 连接成功建立的回调
      this.socketObj.onopen = this.onopenCallback;
      // 连接发生错误的回调
      this.socketObj.onerror = this.onerrorCallback;
      // 连接关闭的回调 
      this.socketObj.onclose = this.oncloseCallback;
      // 向后端发送数据的回调
      this.socketObj.onsend = this.onsendCallback;
      // 接收到消息的回调
      this.socketObj.onmessage = this.getMessageCallback;

      //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
      window.onbeforeunload = () => {
        this.socketObj.close();
      };
    },
    // websocket重连
    socketReconnect() {
      if (this.socketReconnectLock) {
        return;
      }
      this.socketReconnectLock = true;
      this.socketReconnectTimer && clearTimeout(this.socketReconnectTimer);
      this.socketReconnectTimer = setTimeout(() => {
        console.log("WebSocket:重连中...");
        this.socketReconnectLock = false;
        // websocket启动
        this.createWebSocket();
      }, 4000);
    },
    // 连接成功建立的回调
    onopenCallback: function (event) {
      console.log("WebSocket:已连接");
      // 心跳检测重置
      this.heartCheck.reset().start();
    },
    // 连接发生错误的回调
    onerrorCallback: function (event) {
      console.log("WebSocket:发生错误");
      // websocket重连
      this.socketReconnect();
    },
    // 连接关闭的回调
    oncloseCallback: function (event) {
      console.log("WebSocket:已关闭");
      // 心跳检测重置
      this.heartCheck.reset();
      if (!this.socketLeaveFlag) {
        // 没有离开--重连
        // websocket重连
        this.socketReconnect();
      }
    },
    // 向后端发送数据的回调
    onsendCallback: function () {
      console.log("WebSocket:发送信息给后端");
    },
    // 接收到消息的回调
    getMessageCallback: function (msg) {
      console.log(msg);
      // console.log(msg.data);
      if (msg.data.indexOf("HeartBeat") > -1) {
        // 心跳回复——心跳检测重置
        // 收到心跳检测回复就说明连接正常
        console.log("收到心跳检测回复");
        // 心跳检测重置
        this.heartCheck.reset().start();
      } else {
        if (msg.data == "连接成功") {
          return
        }
        let data = JSON.parse(msg.data);
        this.messages.push(data.message);
        // 普通推送——正常处理
        console.log("收到推送消息");
        // 相关处理
      }
    },
  },
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值