hldy_app_mini/common/websocketManager.js

52 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// websocketManager.js
import WsRequest from '@/common/websocket.js';
let globalWs = null;
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;
}
// 强烈建议:全局只 bind 一次WsRequest 内部已用静态保护)
const opt = Object.assign({ bindGlobal: true }, options);
globalWs = new WsRequest(url, opt);
return globalWs;
};
const connectWs = () => {
if (!globalWs) return;
// 如果已经连接,直接返回,避免重复 open
if (globalWs.connected) return;
// 明确表示这是一次主动连接请求,允许自动重连
globalWs.reconnectAttempts = 0;
globalWs._shouldReconnect = true;
globalWs._manualClose = false;
globalWs.open();
};
const closeWs = (manual = true) => {
if (!globalWs) return;
// 主动关闭时先禁止自动重连
if (manual) {
globalWs._shouldReconnect = false;
}
// 传 manual 参数到 close以便内部区分是否允许重连
globalWs.close(1000, 'manager close', !!manual);
// 如果你想下次重新 init 时创建新实例,可以把 globalWs 置空
// globalWs = null;
};
export { initWs, connectWs, closeWs };