1.无心跳,短开连接之后重新连。
class webSocketClass {
  constructor(name) {
    this.lockReconnect = false;
    this.localUrl = "ws://XXXXXX";
    this.wsUrl = "";
    this.globalCallback = null;
    this.userClose = false;
    this.createWebSocket(name);
  }

  createWebSocket(url) {
    let that = this;
    that.wsUrl = url;
    try {
      that.ws = new WebSocket(that.localUrl + that.wsUrl);
      that.initEventHandle();
    } catch (e) {
      that.reconnect(url);
    }
  }

  //初始化
  initEventHandle() {
    let that = this;
    //连接成功建立后响应
    that.ws.onopen = function() {
      console.log("连接成功");
    }; 
    //连接关闭后响应
    that.ws.onclose = function() {
      if (!that.userClose) {
        that.reconnect(that.wsUrl); //重连
      }
    };
    that.ws.onerror = function() {
      if (!that.userClose) {
        that.reconnect(that.wsUrl); //重连
      }
    };
    that.ws.onmessage = function() {
      that.getWebSocketMsg(that.globalCallback);
    };
  }

  reconnect(url) {
    let that = this;
    if (that.lockReconnect) return;
    that.lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多
    setTimeout(function() {
      that.createWebSocket(url);
      that.lockReconnect = false;
    }, 30000);
  }

  webSocketSendMsg(msg) {
    this.ws.send(msg);
  }

  getWebSocketMsg(callback) {
    this.ws.onmessage = ev => {
      callback && callback(ev);
    };
  }

  closeSocket() {
    let that = this;
    if (that.ws) {
      that.userClose = true;
      that.ws.close();
    }
  }
}
export default webSocketClass;

调用方法

import WebSocketClass from '@/services/webSocket';
let ws = new WebSocketClass(url);

关闭方法

ws.closeSocket();

获取socket返回的信息

ws.getWebSocketMsg(ev => {
  console.log(JSON.parse(ev.data));
});

向socket发送消息

ws.webSocketSendMsg(msg);
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐