Hello Every I am building an online game where two users can connect in a lobby and play game basically the error is i cannot listen on event in the server side in the specific room Here is the code
const MAX_USERS_PER_LOBBY = 2;
let lobbies = [];
io.on('connection', (socket) => {
console.log('A user connected');
// Find a lobby with space for the user, or create a new lobby
let lobby = lobbies.find((lobby) => lobby.users.length < MAX_USERS_PER_LOBBY);
if (!lobby) {
lobby = {
id: lobbies.length + 1,
users: []
};
lobbies.push(lobby);
}
// Add the user to the lobby
lobby.users.push(socket.id);
socket.join(`lobby-${lobby.id}`);
console.log(`User ${socket.id} joined lobby ${lobby.id}`);
// Start the game if the lobby is full
if (lobby.users.length === MAX_USERS_PER_LOBBY) {
io.to(`lobby-${lobby.id}`).emit('game_start');
console.log(`Game started in lobby ${lobby.id}`);
// Add event listeners for sending and receiving data
socket.on('send_data', (data) => {
console.log(`Received data from user ${socket.id} in lobby ${lobby.id}:`, data);
socket.to(`lobby-${lobby.id}`).emit('receive_data', data);
});
socket.to(`lobby-${lobby.id}`).emit('receive_data', "welcome");
}
socket.on('disconnect', () => {
console.log(`User ${socket.id} disconnected`);
// Remove the user from the lobby
lobby.users = lobby.users.filter((userId) => userId !== socket.id);
// If the lobby is now empty, remove it
if (lobby.users.length === 0) {
lobbies = lobbies.filter((lobby) => lobby.id !== lobby.id);
console.log(`Lobby ${lobby.id} removed`);
}
});
});
I want to know how can i listen an event on the server side for the specific room