前端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);

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值