Chat room — real-time messaging with user presence.
1const { WebSocketServer } = require("ws");23class ChatRoom {4 constructor() {5 this.rooms = new Map();6 }78 join(roomId, ws, user) {9 if (!this.rooms.has(roomId)) {10 this.rooms.set(roomId, new Map());11 }12 this.rooms.get(roomId).set(ws, user);13 this.broadcast(roomId, {14 type: "user:joined",15 user,16 users: this.getUsers(roomId),17 });18 }1920 leave(roomId, ws) {21 const room = this.rooms.get(roomId);22 if (room) {23 const user = room.get(ws);24 room.delete(ws);25 this.broadcast(roomId, {26 type: "user:left",27 user,28 users: this.getUsers(roomId),29 });30 }31 }3233 message(roomId, ws, text) {34 const user = this.rooms.get(roomId)?.get(ws);35 if (user) {36 this.broadcast(roomId, {37 type: "message",38 user,39 text,40 timestamp: Date.now(),41 });42 }43 }4445 getUsers(roomId) {46 const room = this.rooms.get(roomId);47 return room ? Array.from(room.values()) : [];48 }4950 broadcast(roomId, data) {51 const room = this.rooms.get(roomId);52 if (!room) return;53 const msg = JSON.stringify(data);54 room.forEach((_, ws) => {55 if (ws.readyState === 1) ws.send(msg);56 });57 }58}