EvalueTonSavoir/test/stressTest/class/student.js

60 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-11-15 17:46:01 -05:00
import { io } from "socket.io-client";
export class Student {
constructor(username, roomName) {
this.username = username;
this.roomName = roomName;
this.socket = null;
}
connectToRoom(baseUrl) {
2024-11-15 19:35:41 -05:00
return new Promise((resolve, reject) => {
try {
this.socket = io(baseUrl, {
path: `/api/room/${this.roomName}/socket`,
transports: ['websocket'],
autoConnect: true,
reconnection: true,
reconnectionAttempts: 10,
reconnectionDelay: 10000,
timeout: 20000,
});
2024-11-26 17:04:22 -05:00
2024-11-15 19:35:41 -05:00
this.socket.on('connect', () => {
this.joinRoom(this.roomName, this.username);
2024-11-26 17:04:22 -05:00
this.listenForMessages(); // Start listening for messages
resolve(this.socket);
2024-11-15 19:35:41 -05:00
});
2024-11-26 17:04:22 -05:00
2024-11-15 19:35:41 -05:00
this.socket.on('error', (error) => {
reject(new Error(`Connection error: ${error.message}`));
});
2024-11-26 17:04:22 -05:00
2024-11-15 19:35:41 -05:00
} catch (error) {
2024-11-26 17:04:22 -05:00
console.error(`Error connecting ${this.name} to room ${this.roomName}:`, error.message);
reject(error);
2024-11-15 19:35:41 -05:00
}
2024-11-15 17:46:01 -05:00
});
}
joinRoom(roomName, username) {
if (this.socket) {
this.socket.emit('join-room', { roomName, username });
}
}
2024-11-26 17:04:22 -05:00
sendMessage(message) {
if (this.socket && this.socket.connected) {
this.socket.emit('message-test', { room: this.roomName, message });
}
}
listenForMessages() {
if (this.socket) {
this.socket.on('message-test', (data) => {
console.log(`Message received in room ${this.roomName} by ${this.username}:`, data.message);
});
}
}
2024-11-15 17:46:01 -05:00
}