webSocket Manager

WebSocket 连接管理器,用于统一管理多个 WebSocket 连接。这个管理器特别适用于需要同时维护多个 WebSocket 连接的复杂应用。
该连接管理器请配合,封装好的 uniapp websocket封装 使用。

js 复制代码
import WS from '@/utils/websocket.js'

class WebSocketManager {
  constructor() {
    this.connections = new Map()
  }

  /**
   * 建立或复用 WebSocket 连接
   * @param {string} url WebSocket 地址
   * @param {Function} onMessage 收到消息回调
   */
  connect(url, onMessage) {
    if (this.connections.has(url)) {
      console.log(`复用已有连接: ${url}`)
      return this.connections.get(url)
    }

    console.log(`新建连接: ${url}`)
    const ws = new WS({
      url,
      onConnected: () => {},
      onMessage: (data) => {
        if (onMessage) {
          onMessage(data)
        }
      },
    })

    this.connections.set(url, ws)

    // 自动清理无效连接
    const cleanup = () => {
      if (ws && ws.socketTask) {
        ws.socketTask.onClose(() => {
          console.log(`连接关闭,移除缓存: ${url}`)
          this.connections.delete(url)
        })
      }
    }

    setTimeout(cleanup, 0)

    return ws
  }

  /**
   * 发送消息
   * @param {string} url 目标地址
   * @param {any} message 消息内容
   */
  sendMessage(url, message) {
    const ws = this.connections.get(url)
    if (ws && ws.socketTask) {
      ws.socketTask.send({
        data: JSON.stringify(message),
        fail: (err) => {
          console.error('发送消息失败:', err)
        },
      })
    } else {
      console.warn(`未找到可用连接: ${url}`)
    }
  }

  /**
   * 主动关闭某个连接
   * @param {string} url 地址
   */
  close(url) {
    const ws = this.connections.get(url)
    if (ws) {
      ws.close()
      this.connections.delete(url)
    }
  }

  /**
   * 关闭所有连接(如页面卸载时)
   */
  closeAll() {
    for (const [url, ws] of this.connections.entries()) {
      ws.close()
    }
    this.connections.clear();
    console.log('所有websocket已关闭!')
  }
}

// 导出单例
const wsManager = new WebSocketManager()
export default wsManager

使用

从utils 里面引用连接管理器: import wsManager from '@/utils/webSocketManager.js'

js 复制代码
      let wsUrl = `${wsUrl}/websocket/handheld/ws/notify/${deviceCode}`; // ws地址
      
      // 连接 ws
      wsManager.connect(wsUrl, (data) => {
        console.log('*******ws消息:',data);
      })
js 复制代码
  onUnload() {
    // 关闭所有ws链接
    wsManager.closeAll()
  }
相关推荐
知了学历孙老师1 小时前
小自考的校考和统考,出题方和难度差在哪
java·大数据·前端
ShineWinsu3 小时前
对于JavaScript:操作元素的解析
开发语言·前端·javascript·面试·web·dom·元素
福兮说4 小时前
JSON 格式正确,数据就可靠吗?我用一份自编配置检查类型与空值
java·前端·json
程序员老赵6 小时前
Docker 部署青龙面板:轻松搭建定时任务管理平台
前端·docker·开源
Swot6 小时前
Asciidoctor 公式数字下标错位问题:原因分析与解决方案
前端
Swot6 小时前
leo-editor 中将 Markdown 内容转成 asciidoc 格式
前端
狒狒AI6 小时前
Remotion / GSAP+Three / HyperFrames / Skia 四栈实测:代码渲染知识视频的选栈方法(附开源技能)
前端·人工智能·aigc
修炼的dance6 小时前
浏览器里导出H.265,8.5秒和55.5秒差在硬件
前端
补码缩写6 小时前
WebCodecs选编码器,探测之后还要验解码和播放
前端
大文说跨境6 小时前
亚马逊多账号管理浏览器怎么选?云登/紫鸟/AdsPower 对比
java·前端·自动化