session start works

This commit is contained in:
aodulov
2025-10-10 12:48:06 +03:00
parent 556df015e8
commit 3c192b136c
51 changed files with 29002 additions and 46 deletions

View File

@@ -0,0 +1,85 @@
class WebSocketService {
private ws: WebSocket | null = null;
private messageHandlers: ((message: any) => void)[] = [];
private errorHandlers: ((error: Event) => void)[] = [];
private currentSessionId: string | null = null;
private currentClientId: string | null = null;
connect(sessionId: string, clientId: string) {
// Prevent multiple connections
if (this.ws) {
return;
}
this.currentSessionId = sessionId;
this.currentClientId = clientId;
const wsUrl = `ws://localhost:8000/sessions/${sessionId}`;
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('WebSocket connected');
// Directly send registration message on open
this.sendMessage({ type: 'REGISTER_CLIENT' });
};
this.ws.onmessage = (event) => {
try {
const message = JSON.parse(event.data);
console.log('WebSocketService: Received and parsed message:', message);
this.messageHandlers.forEach(handler => handler(message));
} catch (error) {
console.error('Error parsing incoming message:', error);
}
};
this.ws.onclose = () => {
console.log('WebSocket disconnected');
this.ws = null;
this.currentSessionId = null;
this.currentClientId = null;
};
this.ws.onerror = (event) => {
console.error('WebSocket error:', event);
this.errorHandlers.forEach(handler => handler(event));
};
}
disconnect() {
if (this.ws) {
this.ws.close();
}
}
sendMessage(message: any) {
if (this.ws && this.ws.readyState === WebSocket.OPEN && this.currentClientId && this.currentSessionId) {
const messageToSend = {
...message,
clientId: this.currentClientId,
sessionId: this.currentSessionId,
};
this.ws.send(JSON.stringify(messageToSend));
} else {
// This error can be ignored if it happens during initial connection in StrictMode
// console.error('WebSocket is not connected or clientId/sessionId is missing.');
}
}
onMessage(handler: (message: any) => void) {
this.messageHandlers.push(handler);
}
removeMessageHandler(handler: (message: any) => void) {
this.messageHandlers = this.messageHandlers.filter(h => h !== handler);
}
onError(handler: (error: Event) => void) {
this.errorHandlers.push(handler);
}
removeErrorHandler(handler: (error: Event) => void) {
this.errorHandlers = this.errorHandlers.filter(h => h !== handler);
}
}
export const webSocketService = new WebSocketService();