diff --git a/src/modules/ws-proxy/manager.ts b/src/modules/ws-proxy/manager.ts index 007d27e..1c706f8 100644 --- a/src/modules/ws-proxy/manager.ts +++ b/src/modules/ws-proxy/manager.ts @@ -6,12 +6,40 @@ import { EventEmitter } from 'eventemitter3'; class WsMessage { ws: WebSocket; user?: string; - emitter: EventEmitter;; + emitter: EventEmitter; + private pingTimer?: NodeJS.Timeout; + private readonly PING_INTERVAL = 30000; // 30 秒发送一次 ping + constructor({ ws, user }: WssMessageOptions) { this.ws = ws; this.user = user; this.emitter = new EventEmitter(); + this.startPing(); } + + private startPing() { + this.stopPing(); + this.pingTimer = setInterval(() => { + if (this.ws.readyState === WebSocket.OPEN) { + this.ws.ping(); + } else { + this.stopPing(); + } + }, this.PING_INTERVAL); + } + + private stopPing() { + if (this.pingTimer) { + clearInterval(this.pingTimer); + this.pingTimer = undefined; + } + } + + destroy() { + this.stopPing(); + this.emitter.removeAllListeners(); + } + async sendResponse(data: any) { if (data.id) { this.emitter.emit(data.id, data?.data); @@ -60,6 +88,7 @@ export class WsProxyManager { const value = this.wssMap.get(id); if (value) { value.ws.close(); + value.destroy(); } } const [username, appId] = id.split('-'); @@ -72,6 +101,7 @@ export class WsProxyManager { const value = this.wssMap.get(id); if (value) { value.ws.close(); + value.destroy(); } this.wssMap.delete(id); }