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)
相关推荐
0思必得019 分钟前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice21 分钟前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶36022 分钟前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额1 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
爱喝白开水a3 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌413 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡4 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone4 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09014 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农4 小时前
Vue 2.3
前端·javascript·vue.js