socket连接封装

效果:

javascript 复制代码
class websocketMessage {
  constructor(params) {
    this.params = params; // 传入的参数
    this.socket = null;
    this.lockReconnect = false; // 重连的锁
    this.socketTimer = null; // 心跳
    this.lockTimer = null; // 重连
    this.timeout = 3000; // 发送消息
    this.callbacks = []; // 存储外部的回调函数
    // this.init(); // websocket 初始化
  }

  /**
   * @description: websocket 初始化
   * @return {*}
   */
  init() {
    if (!("WebSocket" in window)) {
      console.warn("当前浏览器不支持 WebSocket");
      return;
    }

    this.lockReconnect = false;
    this.socket = new WebSocket(this.params.ws);
    this.socket.onopen = this.open.bind(this);
    this.socket.onmessage = this.onMessage.bind(this);
    this.socket.onerror = this.error.bind(this);
    // this.socket.onclose = this.close.bind(this);
  }

  /**
   * @description: websocket 已连接
   * @return {*}
   */
  open() {
    console.log(`${this.params.ws}:WebSocket已连接。`);
  }

  /**
   * @description: 监听接收消息
   * @param {*} event
   * @return {*}
   */
  onMessage({
    data
  }) {


    // 判断是否开启心跳
    if (this.params.heart) {
      this.socketTimer && clearTimeout(this.socketTimer);
      this.socketTimer = setTimeout(() => {
        this.socket.send(JSON.stringify(this.params.heart.data));
      }, 3000);
    }

    // 如果开启心跳,过滤掉心跳的数据
    if (data === this.params?.heart?.data) {
      return;
    }
    // 将消息传递给所有注册的回调函数
    this.callbacks.forEach((callback) => callback(typeof data === 'string' ? data : JSON.parse(data)));
  }

  /**
   * @description: 注册消息回调函数
   * @param {*} callback 回调函数
   * @return {*}
   */
  message(callback) {
    if (typeof callback === "function") {
      this.callbacks.push(callback);
    } else {
      console.warn("注册的回调必须是一个函数");
    }
  }

  /**
   * @description: 发送消息
   * @param {*} msg
   * @return {*}
   */
  send(msg) {
    if (!this.socket) {
      return;
    }
    let timer = null;
    clearTimeout(timer);
    timer = setTimeout(() => {
      if (this.socket?.readyState === 1) {
        this.socket.send(JSON.stringify(msg));
        clearTimeout(timer);
      } else {
        this.send(msg);
      }
    }, 50);
  }

  /**
   * @description: 连接发送错误的时候,输出信息
   * @param {*} e 错误消息
   * @return {*}
   */
  error(e) {
    this.socket = null;
    console.log(`${this.params.ws}:WebSocket正在重新连接`, e);
    this.reconnect();
  }

  /**
   * @description: 关闭 websocket 连接
   * @return {*}
   */
  close() {
    this.socket = null;
    this.lockReconnect = true;
    this.callbacks = []; // 清除回调
    clearTimeout(this.lockTimer);
    clearTimeout(this.socketTimer);
    this.socket?.onclose();
    console.log(`${this.params.ws}:WebSocket连接已关闭`);
  }

  /**
   * @description: 重新连接 websocket
   * @return {*}
   */
  reconnect() {
    if (this.lockReconnect) {
      return;
    }
    this.lockReconnect = true;
    clearTimeout(this.lockTimer);
    this.lockTimer = setTimeout(() => {
      this.init();
    }, this.timeout);
  }
}



// 调用:
let socket = new websocketMessage({
  ws: "wss://toolin.cn/echo",
});

socket.init();

// 注册消息处理回调
socket.message((data) => {
  console.log("接收到的消息:", data);
});

// 发送登录消息
socket.send({
  type: "login",
  data: {
    userId: "123",
  },
});
setTimeout(() => {

  // 发送登录消息
  socket.send({
    type: "sadfasd",
    data: {
      userId: "sadf",
    },
  });
}, 5000)
setTimeout(() => {

  // 发送登录消息
  socket.send({
    type: "20000",
    data: {
      userId: "2",
    },
  });
}, 2000)
相关推荐
codeGoogle4 小时前
自研 IM 还是选择第三方 SDK?企业开发者应该如何权衡?
前端·后端·程序员
用户938515635075 小时前
React Context 与自定义 Hook 从底层到实践:「跨层级通信 + 副作用封装」全解析
前端·javascript·react.js
滴滴答答哒5 小时前
VUE3+element-plus MultiSelect 多选下拉组件
前端·javascript·vue.js
其美杰布-富贵-李5 小时前
04 watch 与 Vue 响应式数据流
前端·javascript·vue.js
赵大仁7 小时前
生成式 UI 实战:用 JSON Schema + React 动态渲染 AI 界面
前端·ai·react·next.js·前端架构·生成式ui
kyriewen8 小时前
我排查了一个React内存泄漏——罪魁祸首是这3个被忽略的清理函数
前端·javascript·面试
IT_陈寒8 小时前
我又被JavaScript的隐式类型转换坑了
前端·人工智能·后端
其美杰布-富贵-李9 小时前
03 ref、reactive 与 computed 响应式数据
前端·javascript·vue.js
OpenTiny社区9 小时前
GenUI SDK v1.3.0 发布|多框架兼容,一键换物料,渲染器 & 演练场全面增强!
前端·ai编程
用户938515635079 小时前
useRef + Web Worker 实战:React 如何优雅地拥抱多线程
前端·javascript·react.js