Calling socket.to(room).emit(...) delivers to every other peer in the room, excluding the sender. Calling io.to(room).emit(...) delivers to everyone.
When a connection terminates or drops, RoomRegistry automatically purges that socket identifier from all active rooms in O(1) time without manual cleanup.
1io.onConnection((socket) => {1 const userId = String(socket.metadata.userId);11 // 1. Join Room & Broadcast Presence1 socket.on("room.join", (data: { room?: string }, ack) => {1 if (!data?.room) return ack?.({ ok: false, error: "room name required" });21 socket.join(data.room);1 // Notify other peers in room (excludes caller)1 socket.to(data.room).emit("room.peer-joined", { room: data.room, userId });1 ack?.({ ok: true, room: data.room });1 });31 // 2. Room Messaging (Excludes caller automatically)1 socket.on("room.message", (data: { room?: string; text?: string }, ack) => {1 if (!data?.room || !data.text) {1 return ack?.({ ok: false, error: "Missing room or text payload" });1 }1 socket.to(data.room).emit("room.message", { from: userId, text: data.text });1 ack?.({ ok: true });2 });41 // 3. Voluntary Leave1 socket.on("room.leave", (data: { room?: string }, ack) => {1 if (!data?.room) return ack?.({ ok: false, error: "room required" });51 socket.leave(data.room);1 socket.to(data.room).emit("room.peer-left", { room: data.room, userId });2 ack?.({ ok: true });3 });1});