WebSocket使用

94 阅读1分钟
<script>
const heartCheck = {
  timeout: 6 * 1000,
  timer: null,
  serverTimer: null,
  reset() {
    this.timer && clearTimeout(this.timer);
    this.serverTimer && clearTimeout(this.serverTimer);
  },
  start(ws, params = "ping") {
    this.reset();
    this.timer = setTimeout(() => {
      // console.log('发送心跳,后端收到后,返回一个心跳消息')
      // onmessage拿到返回的心跳就说明连接正常
      ws.send(params);
      this.serverTimer = setTimeout(() => {
        // 如果超过一定时间还没响应(响应后触发重置),说明后端断开了
        ws.close();
      }, this.timeout);
    }, this.timeout);
  },
};
export default {
 data() {
     let origin = window.location.origin; //测试环境
    if (process.env.NODE_ENV == "production") {
      origin = window.location.origin;  //正式环境
    }
    let wsuri = (origin + "/ws/").replace("http", "ws");
    return {
      wsuri, // ws wss
      lockReconnect: false, // 连接失败不进行重连
      maxReconnect: 10, // 最大重连次数,若连接失败
      socket: null,
      queryParams: "ping",  //发送心跳数据
      userId:""
    }
 },
 mounted() {
    this.initWebSocket();
    window.addEventListener("beforeunload", (e) => this.beforeunloadHandler(e)); //监听页面刷新触发事件
    // this.$refs.text.focus();
  },
  //销毁websoket 移除监听页面刷新触发事件
  beforeDestroy() {
    this.beforeunloadHandler();
    setTimeout(() => {
      this.$destroy();
    }, 1000);
    window.removeEventListener("beforeunload", (e) =>
      this.beforeunloadHandler(e)
    );
  },
  methods: {
    //刷新浏览器 关闭websoket
    beforeunloadHandler() {
      heartCheck.reset();
      this.lockReconnect = false;
      this.socket && this.socket.close();
      console.log("关闭websoket");
    },
    //WebSocket  开始
    initWebSocket() {
      try {
        if ("WebSocket" in window) {
          this.socket = new WebSocket(this.wsuri + this.userId);
        } else {
          this.$message.error("您的浏览器不支持websocket");
          console.log("您的浏览器不支持websocket");
        }
        this.socket.onopen = this.websocketonopen;
        this.socket.onmessage = this.websocketonmessage;
        this.socket.onclose = this.websocketclose;
        this.socket.onerror = this.websocketonerror;
      } catch (e) {
        console.error("e: ", e);
      }
    },
    websocketonopen() {
      console.log("WebSocket连接成功", this.socket.readyState);
      this.maxReconnect = 10;
      heartCheck.start(this.socket, this.queryParams);
      this.websocketsend();
    },
    ///WebSocket 发送心跳
    websocketsend() {
      this.socket.send(this.queryParams);
    },
    ///WebSocket 接受消息
    websocketonmessage(e) {
      try {
        // console.log("WebSocket获取数据", e);
        // 消息获取成功,重置心跳
        heartCheck.start(this.socket, this.queryParams);
        if (e.data !== "pong") {
          let msg = JSON.parse(e.data);
          console.log(msg, "收到消息");
        }
      } catch (e) {
        console.error("e: ", e);
      }
    },
    ///WebSocket 关闭
    websocketclose(e) {
      console.log("connection closed (" + e.code + ")");
      this.reconnect();
    },
    ///WebSocket 发生错误
    websocketonerror(e) {
      console.log("WebSocket连接发生错误", e);
      this.reconnect();
    },
    ///WebSocket 发生重连
    reconnect() {
      console.log("尝试重连");
      this.socket && this.socket.close();
      if (this.lockReconnect || this.maxReconnect <= 0) return;
      console.log("连接中");
      setTimeout(() => {
        this.maxReconnect--; // 不做限制 连不上一直重连
        this.initWebSocket();
      }, 6 * 1000);
    },
    //WebSocket  结束

}

</script>