hldy_app_mini/common/websocketManager.js

52 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

2025-12-30 08:40:09 +08:00
// websocketManager.js
import WsRequest from '@/common/websocket.js';
let globalWs = null;
2026-01-19 17:35:31 +08:00
const initWs = (url, options = {}) => {
// 如果已经有 WebSocket 实例且 URL 相同,直接返回
if (globalWs) {
if (globalWs.url === url) {
return globalWs;
}
// 否则先将旧实例以“手动关闭”方式关闭并清理,避免旧实例干扰
try {
globalWs._shouldReconnect = false;
globalWs.close(1000, 'reinit', true);
} catch (e) {
// 忽略关闭错误
}
globalWs = null;
}
2025-12-30 08:40:09 +08:00
2026-01-19 17:35:31 +08:00
// 强烈建议:全局只 bind 一次WsRequest 内部已用静态保护)
const opt = Object.assign({ bindGlobal: true }, options);
globalWs = new WsRequest(url, opt);
2025-12-30 08:40:09 +08:00
return globalWs;
};
const connectWs = () => {
2026-01-19 17:35:31 +08:00
if (!globalWs) return;
// 如果已经连接,直接返回,避免重复 open
if (globalWs.connected) return;
// 明确表示这是一次主动连接请求,允许自动重连
globalWs.reconnectAttempts = 0;
globalWs._shouldReconnect = true;
globalWs._manualClose = false;
globalWs.open();
2025-12-30 08:40:09 +08:00
};
2026-01-19 17:35:31 +08:00
const closeWs = (manual = true) => {
if (!globalWs) return;
// 主动关闭时先禁止自动重连
if (manual) {
globalWs._shouldReconnect = false;
2025-12-30 08:40:09 +08:00
}
2026-01-19 17:35:31 +08:00
// 传 manual 参数到 close以便内部区分是否允许重连
globalWs.close(1000, 'manager close', !!manual);
// 如果你想下次重新 init 时创建新实例,可以把 globalWs 置空
// globalWs = null;
2025-12-30 08:40:09 +08:00
};
export { initWs, connectWs, closeWs };