添加心跳机制以保持 WebSocket 连接,优化连接关闭时的资源清理
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user