前端websocket实体类,开箱即用

前端websocket实体类,开箱即用

class WebSocketUtil {
  //isReady默认是false,不自动重连
  constructor(data, callback, isReady = false) {
    this.wsData = data;
    this.callback = callback;
    this.isReady = isReady;
    this.createWebSocket();
  }

  reconnect() {
    if (this.wsData.lockReconnect) {
      return;
    }
    const _this = this;
    this.wsData.lockReconnect = true;
    // 没连接上会一直重连,设置延迟避免请求过多
    this.wsData.tt && clearTimeout(this.wsData.tt);
    this.wsData.tt = setTimeout(function () {
      _this.createWebSocket();
      _this.wsData.lockReconnect = false;
    }, 4000);
  }

  isOpen(ws) {
    return ws.readyState === ws.OPEN;
  }

  createWebSocket() {
    const _this = this;
    const heartCheck = {
      // 心跳
      timeout: 20000, // 心跳每20秒发一次
      timeoutObj: null,
      serverTimeoutObj: null,
      start: function () {
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        // this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function () {
          if (_this.wsData.ws.readyState == 3 && _this.isReady) {
            _this.reconnect();
            return;
          }
          if (!_this.isOpen(_this.wsData.ws)) {
            clearTimeout(self.timeoutObj);
            return;
          }
          _this.wsData.ws.send(
            JSON.stringify({
              type: -1,
            })
          );
        }, this.timeout);
      },
    };
    try {
      if (this.wsData.ws) {
        this.wsData.ws.close();
      }
      const key = `bearer${sessionStorage.getItem("YJZN_TOKEN")}`;
      this.wsData.ws = new WebSocket(`${this.wsData.wsUrl}`, key);
    } catch (error) {
      //
      console.log("error catch", error);
      this.reconnect(_this.wsData);
      return;
    }

    this.wsData.ws.onopen = function () {
      // 这里用一个延时器模拟事件
      console.log("webscoket onOpen", _this.wsData);
      // 心跳检测重置
      heartCheck.start();
    };

    this.wsData.ws.onmessage = function (e) {
      // 这里接受服务器端发过来的消息
      let data = null;
      try {
        data = JSON.parse(e.data);
      } catch (error) {
        data = e ? e.data : null;
      }
      _this.callback(data);
      // 心跳检测重置
      heartCheck.start();
    };
    this.wsData.ws.onclose = () => {
      console.log("websocket onclose", _this.wsData);
      _this.isReady && this.reconnect(_this.wsData);
    };
    this.wsData.ws.onerror = () => {
      console.log("webscoket onerror", _this.wsData);
      _this.isReady && this.reconnect(_this.wsData);
    };
  }

  getData() {
    return this.wsData;
  }
}

export default WebSocketUtil;

export const webSocketClient = (data, callback) => {
  return new WebSocketUtil(data, callback);
};

使用方法

import { webSocketClient } from '@/utils/websocket';
const fnws = {
    wsUrl: '',
    lockReconnect: false,
    ws: null,
    tt: null
};

 if (fnws.ws) {
      fnws.ws.close();
 }
fnws.wsUrl = `${location.protocol.indexOf('https') != -1 ? 'wss' : 'ws'}://${location.host}/ncxjws/alarmWs`;
//调用即可       
webSocketClient(fnws, this.handMsg);

你可能感兴趣的:(websocket,javascript,前端)