From bd7525efb0b23f7f662bdd097fb2fd24d3217122 Mon Sep 17 00:00:00 2001 From: abearxiong Date: Thu, 5 Feb 2026 04:58:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=BF=83=E8=B7=B3=E6=9C=BA?= =?UTF-8?q?=E5=88=B6=E4=BB=A5=E4=BF=9D=E6=8C=81=20WebSocket=20=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=EF=BC=8C=E4=BC=98=E5=8C=96=E8=BF=9E=E6=8E=A5=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E6=97=B6=E7=9A=84=E8=B5=84=E6=BA=90=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/modules/ws-proxy/manager.ts | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) 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); }