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)
相关推荐
天天扭码21 小时前
如何实现流式输出?一篇文章手把手教你!
前端·aigc·ai编程
前端 贾公子21 小时前
vue移动端适配方案 === postcss-px-to-viewport
前端·javascript·html
GISer_Jing1 天前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
明远湖之鱼1 天前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长1 天前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs1 天前
Nginx核心架构设计
运维·前端·nginx
雪球工程师团队1 天前
别再“苦力”写后台,Spec Coding “跑” 起来
前端·ai编程
m0_471199631 天前
【场景】前端怎么解决离线收银、数据同步异常等场景问题
前端·javascript
Curvatureflight1 天前
前端性能优化实战:从3秒到300ms的加载速度提升
前端·人工智能·性能优化