1. Keep session alive with ping-pong. 2. Refreshed tests.

This commit is contained in:
AG
2025-10-16 10:48:11 +03:00
parent 6f64b1daca
commit 95684a34f7
27 changed files with 420 additions and 100 deletions

View File

@@ -15,6 +15,7 @@ class WebSocketService {
private sessionTerminatedHandlers: (() => void)[] = [];
private currentSessionId: string | null = null;
private currentClientId: string | null = null;
private heartbeatInterval: NodeJS.Timeout | null = null;
connect(sessionId: string, clientId: string) {
// Prevent multiple connections
@@ -33,6 +34,13 @@ class WebSocketService {
console.log('WebSocket connected');
// Directly send registration message on open
this.sendMessage({ type: 'REGISTER_CLIENT' });
// Start heartbeat to keep connection alive
this.heartbeatInterval = setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ type: 'PING', clientId: this.currentClientId, sessionId: this.currentSessionId }));
}
}, 30000); // Send ping every 30 seconds
};
this.ws.onmessage = (event) => {
@@ -47,6 +55,10 @@ class WebSocketService {
this.ws.onclose = () => {
console.log('WebSocket disconnected');
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
this.sessionTerminatedHandlers.forEach(handler => handler());
this.ws = null;
this.currentSessionId = null;
@@ -55,14 +67,26 @@ class WebSocketService {
this.ws.onerror = (event) => {
console.error('WebSocket error:', event);
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
this.errorHandlers.forEach(handler => handler(event));
};
}
disconnect() {
if (this.ws) {
this.ws.close();
}
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
}
sendMessage(message: any) {