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()
}