Spaces:
Sleeping
Sleeping
| import WebSocket from 'ws'; | |
| export class RoomManager { | |
| // Map<RoomId, Map<Username, WebSocket>> | |
| rooms; | |
| constructor() { | |
| this.rooms = new Map(); | |
| } | |
| /** | |
| * Adds a user to a specific room. | |
| * Creates the room if it doesn't exist. | |
| */ | |
| joinRoom(roomId, username, socket) { | |
| if (!this.rooms.has(roomId)) { | |
| this.rooms.set(roomId, new Map()); | |
| } | |
| this.rooms.get(roomId)?.set(username, socket); | |
| } | |
| renameUser(roomId, username, newUsername, socket) { | |
| const room = this.rooms.get(roomId); | |
| if (!room) | |
| return false; | |
| if (!room.has(username)) | |
| return false; | |
| if (room.has(newUsername)) | |
| return false; | |
| // Remove old username | |
| room.delete(username); | |
| // Add new username with same socket | |
| room.set(newUsername, socket); | |
| return true; | |
| } | |
| /** | |
| * Removes a user from a room. | |
| * Cleans up the room if it becomes empty. | |
| */ | |
| leaveRoom(roomId, username) { | |
| const room = this.rooms.get(roomId); | |
| if (room) { | |
| const deleted = room.delete(username); | |
| if (room.size === 0) { | |
| this.rooms.delete(roomId); | |
| } | |
| return deleted; | |
| } | |
| return false; | |
| } | |
| /** | |
| * Checks if a room exists. | |
| */ | |
| hasRoom(roomId) { | |
| return this.rooms.has(roomId); | |
| } | |
| /** | |
| * Sends a message to all users in a specific room. | |
| */ | |
| broadcast(roomId, message) { | |
| const room = this.rooms.get(roomId); | |
| if (!room) | |
| return; | |
| for (const client of room.values()) { | |
| if (client.readyState === WebSocket.OPEN) { | |
| client.send(message); | |
| } | |
| } | |
| } | |
| } | |
| //# sourceMappingURL=RoomManager.js.map |