EvalueTonSavoir/test/stressTest/class/roomParticipant.js

83 lines
2.4 KiB
JavaScript
Raw Normal View History

2024-11-27 18:36:59 -05:00
import { io } from "socket.io-client";
export class RoomParticipant {
constructor(username, roomName) {
this.username = username;
this.roomName = roomName;
this.socket = null;
this.maxRetries = 3;
this.retryDelay = 1000;
}
2024-11-28 15:09:22 -05:00
async connectToRoom(baseUrl) {
2024-11-27 18:36:59 -05:00
let retries = 0;
2024-11-28 15:09:22 -05:00
const maxRetries = 2;
const retryDelay = 2000;
2024-11-27 18:36:59 -05:00
2024-11-28 15:09:22 -05:00
const cleanup = () => {
if (this.socket) {
this.socket.removeAllListeners();
this.socket.disconnect();
this.socket = null;
}
};
2024-11-27 18:36:59 -05:00
2024-11-28 15:09:22 -05:00
while (retries < maxRetries) {
try {
const socket = io(baseUrl, {
path: `/api/room/${this.roomName}/socket`,
transports: ['websocket'],
timeout: 8000,
reconnection: false,
forceNew: true
});
const result = await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
cleanup();
2024-11-27 18:36:59 -05:00
reject(new Error('Connection timeout'));
2024-11-28 15:09:22 -05:00
}, 8000);
2024-11-27 18:36:59 -05:00
socket.on('connect', () => {
2024-11-28 15:09:22 -05:00
clearTimeout(timeout);
2024-11-27 18:36:59 -05:00
this.socket = socket;
2024-11-28 15:09:22 -05:00
this.onConnected(); // Add this line
2024-11-27 18:36:59 -05:00
resolve(socket);
});
socket.on('connect_error', (error) => {
2024-11-28 15:09:22 -05:00
clearTimeout(timeout);
cleanup();
2024-11-27 18:36:59 -05:00
reject(new Error(`Connection error: ${error.message}`));
});
2024-11-28 15:09:22 -05:00
socket.on('error', (error) => {
clearTimeout(timeout);
cleanup();
reject(new Error(`Socket error: ${error.message}`));
});
});
return result;
2024-11-27 18:36:59 -05:00
} catch (error) {
retries++;
2024-11-28 15:09:22 -05:00
if (retries === maxRetries) {
throw error;
2024-11-27 18:36:59 -05:00
}
2024-11-28 15:09:22 -05:00
await new Promise(resolve => setTimeout(resolve, retryDelay));
2024-11-27 18:36:59 -05:00
}
}
}
2024-11-28 15:09:22 -05:00
onConnected() {
// To be implemented by child classes
}
2024-11-27 18:36:59 -05:00
disconnect() {
if (this.socket) {
this.socket.disconnect();
this.socket = null;
}
}
}