import SockJS from 'sockjs-client'; import { Client, IFrame, IMessage, StompSubscription } from '@stomp/stompjs'; import Units from "../units"; /** * 使用方法: * const webSocket= WebSocket.getInstance(WS_URL); // 创建连接 * const subscribe = webSocket.subscribe('/topic/test',{}, (val)=>{console.log("推送的数据:",val)}); // 订阅 * subscribe.unsubscribe(); // 销毁订阅 * webSocket.disconnect(); // 关闭连接 */ // 获取订阅地址 const getWebSocketConfig = (path, options) => { const serverKey = options.serverKey; const header = options.connectionHeaders || {}; const programCode = header.programCode || Units.programCode(serverKey); let server = new URL(options.hydrocarbonServer ? options.hydrocarbonServer : Units.api(serverKey)); let hydrocarbonToken = null; if (header?.hydrocarbonToken) { hydrocarbonToken = header.hydrocarbonToken; } else if (serverKey) { hydrocarbonToken = Units.serverHydrocarbonToken(serverKey) } else if (Units.hydrocarbonToken(programCode)) { hydrocarbonToken = Units.hydrocarbonToken(programCode); } else { hydrocarbonToken = Units.getAnoHydrocarbonToken() } const { protocol, host, pathname } = server; const url = `${protocol}//${host}${pathname}${pathname.endsWith('/') ? '' : '/'}${path}`; return { url, hydrocarbonToken, programCode }; } export interface WebSocketOptions { reconnectDelay?: number; // 重连间隔(ms) maxReconnectAttempts?: number; // 最大重连次数 heartbeatIncoming?: number; // 接收心跳最大间隔 heartbeatOutgoing?: number; // 发送心跳最小间隔 debug?: boolean; // 是否开启调试日志 connectionHeaders?: { [key: string]: string }; // 创建连接请求头信息 } // 全局订阅Map类型 interface SubscriptionRecord { topic: string; callback: (message: any, rawMessage: IMessage) => void; subscription: StompSubscription | null; } // 订阅队列 interface QueuedOperation { type: 'SUBSCRIBE' | 'SEND'; payload: any; } // 连接状态枚举 enum ConnectionState { DISCONNECTED = 'DISCONNECTED', // 断开 CONNECTING = 'CONNECTING', // 连接中 CONNECTED = 'CONNECTED', // 已连接 RECONNECTING = 'RECONNECTING', // 重连中 } class WebSocket { private static instances = new Map(); /** * 获取单例实例的唯一入口 * @param url WebSocket 服务器地址 * @param options 配置项 * @returns 返回对应 URL 的唯一 WebSocket 实例 */ public static getInstance(url: string, options: WebSocketOptions = {}): WebSocket { if (!WebSocket.instances.has(url)) { // 注意:这里调用的是私有的构造函数 const instance = new WebSocket(url, options); WebSocket.instances.set(url, instance); } return WebSocket.instances.get(url)!; } /** * 私有构造函数 * 防止外部直接使用 new WebSocket() 导致单例失效 */ private constructor(url: string, options: WebSocketOptions = {}) { this.url = url; this.config = { ...this.config, ...options }; this.connect(); } private url: string; private client: Client | null = null; private subscriptions = new Map(); private operationQueue: QueuedOperation[] = []; private state: ConnectionState = ConnectionState.DISCONNECTED; private reconnectAttempts = 0; private reconnectTimer: any = null; private connectPromises = new Map void; reject: (error: Error) => void }>(); private config: Required = { reconnectDelay: 5000, maxReconnectAttempts: 5, heartbeatIncoming: 10000, heartbeatOutgoing: 10000, debug: false, connectionHeaders: {}, }; // 建立连接 public connect(): Promise { if (this.state === ConnectionState.CONNECTED) { // 当前已连接不重复创建连接 return Promise.resolve(); } this.state = ConnectionState.CONNECTING; const { url: wsUrl, hydrocarbonToken, programCode } = getWebSocketConfig(this.url, this.config); return new Promise((resolve, reject) => { const currentPromiseId = Date.now().toString(); this.connectPromises.set(currentPromiseId, { resolve, reject }); const { heartbeatIncoming, heartbeatOutgoing, reconnectDelay } = this.config; const socket = new SockJS(wsUrl); this.client = new Client({ webSocketFactory: () => socket, debug: this.config.debug ? (str) => console.log('[STOMP]', str) : () => { }, heartbeatIncoming, heartbeatOutgoing, reconnectDelay, connectHeaders: { "hydrocarbon-token": hydrocarbonToken, "hydrocarbon-program-token": programCode }, onConnect: (frame) => { // 连接成功回调 // console.log("连接成功:frame", frame); this.state = ConnectionState.CONNECTED; this.reconnectAttempts = 0; this.connectPromises.forEach(({ resolve }) => resolve()); this.connectPromises.clear(); this._restoreSubscriptions(); this._flushQueue().catch(console.error); }, onStompError: (frame: IFrame) => { console.error('[WS] ❌ STOMP 协议错误', frame); const error = new Error(frame.headers['message'] || 'STOMP Error'); if (this.state !== ConnectionState.DISCONNECTED) { this.state = ConnectionState.DISCONNECTED; this.client = null; this._scheduleReconnect(); } this.connectPromises.forEach(({ reject }) => reject(error)); this.connectPromises.clear(); }, onWebSocketClose: () => { if ([ConnectionState.CONNECTED, ConnectionState.CONNECTING].includes(this.state)) { console.warn('[WS] ⚠️ 连接意外断开,准备重连...'); this.state = ConnectionState.DISCONNECTED; this.client = null; this._scheduleReconnect(); // 断开重连 } }, onWebSocketError: (error) => { console.error('[WS] ❌ WebSocket 错误', error); const wsError = new Error('WebSocket Error'); if (this.state !== ConnectionState.DISCONNECTED) { this.state = ConnectionState.DISCONNECTED; this.client = null; this._scheduleReconnect(); } this.connectPromises.forEach(({ reject }) => reject(wsError)); this.connectPromises.clear(); }, }); this.client.activate(); }); } // 订阅请求 public async subscribe(topic: string, params: { [key: string]: any }, callback: (message: T, rawMessage: IMessage) => void): Promise { if (this.state === ConnectionState.CONNECTED && this.client) { return this._doSubscribe(topic, callback, params); } else { return new Promise((resolve, reject) => { this.operationQueue.push({ type: 'SUBSCRIBE', payload: { topic, callback, resolve, reject, params }, }); }); } } // 执行实际订阅 private _doSubscribe(topic: string, callback: (message: T, rawMessage: IMessage) => void, params: { [key: string]: any }): Promise { return new Promise((resolve, reject) => { if (!this.client) { reject(new Error('Client not initialized')); return; } try { const stompSub = this.client.subscribe(topic, (message: IMessage) => { try { let body: any = message.body; if (typeof message.body === 'string') { body = JSON.parse(message.body); } callback(body, message); } catch (e) { console.error('[WS] JSON 解析错误', e); callback(message.body as any, message); } }, params || {}); // 3. 更新内存记录 this.subscriptions.set(topic, { topic, callback, subscription: stompSub // 关键:确保新的 subscription 对象被保存 }); resolve(stompSub); } catch (error) { reject(error); } }); } // 发送消息 public send(destination: string, body: any): void { if (this.state === ConnectionState.CONNECTED && this.client) { try { this.client.publish({ destination, body: typeof body === 'string' ? body : JSON.stringify(body), headers: { 'content-type': 'application/json' }, }); } catch (error) { console.error('[WS] 发送消息失败:', error); } } else { this.operationQueue.push({ type: 'SEND', payload: { destination, body } }); } } // 取消订阅 public unsubscribe(topic: string): boolean { const record = this.subscriptions.get(topic); if (record) { record.subscription?.unsubscribe(); this.subscriptions.delete(topic); console.log(`[WS] 🚫 已取消订阅: ${topic}`); return true; } return false; } // 取消所有订阅 public unsubscribeAll(): void { this.subscriptions.forEach((record) => { record.subscription?.unsubscribe(); }); this.subscriptions.clear(); console.log('[WS] 🚫 已取消所有订阅'); } // 断开连接 public disconnect(): void { this.state = ConnectionState.DISCONNECTED; if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } if (this.client) { WebSocket.instances.delete(this.client.webSocket.url); this.client.deactivate(); this.client = null; } this.unsubscribeAll(); this.operationQueue = []; this.connectPromises.forEach(({ reject }) => { reject(new Error('Connection manually disconnected')); }); this.connectPromises.clear(); console.log('[WS] 🔌 客户端已主动断开'); } // 当前订阅数量 public getSubscriptionCount(): number { return this.subscriptions.size; } // 连接后恢复订阅 private _restoreSubscriptions() { if (this.subscriptions.size === 0 || !this.client) return; console.log(`[WS] 🔄 正在恢复 ${this.subscriptions.size} 个订阅...`); this.subscriptions.forEach((record, topic) => { try { const stompSub = this.client.subscribe(topic, (message: IMessage) => { try { let body: any = message.body; if (typeof message.body === 'string') { body = JSON.parse(message.body); } record.callback(body, message); } catch (e) { record.callback(message.body, message); } }); record.subscription = stompSub; } catch (error) { console.error(`[WS] 恢复订阅失败: ${topic}`, error); } }); } // 订阅队列 private async _flushQueue() { if (this.operationQueue.length === 0) return; // console.log(`[WS] 🚀 正在执行 ${this.operationQueue.length} 个排队操作...`); const queue = [...this.operationQueue]; this.operationQueue = []; for (const op of queue) { try { if (op.type === 'SUBSCRIBE') { const { topic, callback, resolve, reject, params } = op.payload; try { const subscription = await this._doSubscribe(topic, callback, params); resolve(subscription); } catch (error) { reject(error); } } else if (op.type === 'SEND') { const { destination, body } = op.payload; this.send(destination, body); } } catch (error) { console.error('[WS] 执行队列操作失败:', error); } } } // 断连重连 private _scheduleReconnect() { if (this.reconnectAttempts >= this.config.maxReconnectAttempts) { console.error('[WS] ❌ 重连失败:达到最大尝试次数'); return; } if (![ConnectionState.RECONNECTING, ConnectionState.DISCONNECTED].includes(this.state)) { return; } this.reconnectAttempts++; const delay = Math.min(this.config.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1), 60000); console.log(`[WS] ⏱️ ${delay}ms 后进行第 ${this.reconnectAttempts} 次重连...`); this.reconnectTimer = setTimeout(() => { this.connect().catch((err) => { if (this.state !== ConnectionState.DISCONNECTED) { console.error('[WS] 重连尝试异常:', err); } }); }, delay); } // 判断是否已连接 public isConnected(): boolean { return this.state === ConnectionState.CONNECTED; } // 获取所有订阅的topic public getSubscribedTopics(): string[] { return Array.from(this.subscriptions.keys()); } } export default WebSocket;