Challenge 1: Translate a Raw ws Broadcast to Socket.IO — Possible Solution ==================================================================== RAW ws (from Chapter 3): const clients = new Set(); wss.on("connection", (socket) => { clients.add(socket); socket.on("message", (data) => { for (const client of clients) { if (client.readyState === client.OPEN) { client.send(data.toString()); } } }); socket.on("close", () => clients.delete(socket)); }); SOCKET.IO EQUIVALENT: io.on("connection", (socket) => { socket.on("message", (data) => { io.emit("message", data); // broadcasts to every connected client }); }); WHY THIS WORKS -------------- - The entire "clients" Set, the manual .add()/.delete() bookkeeping, and the readyState-checked for-loop are ALL replaced by Socket.IO's own internal connection tracking — io.emit(...) already knows about every currently-connected client and only sends to ones that are actually still open, without the application needing to maintain that list itself. - There's no separate "close" handler needed just to stop tracking a disconnected client for broadcast purposes — Socket.IO removes a disconnected client from its own internal registry automatically the moment the underlying connection closes. - The Chapter 3 version deliberately broadcasts to EVERY client including the original sender (data.toString() sent back to the whole "clients" Set, which still contains the sender's own socket). io.emit(...) matches that same "send to everyone, including the sender" behavior — if the goal were "everyone except the sender," Socket.IO's socket.broadcast.emit(...) would be the correct equivalent instead. - This side-by-side is exactly the trade this chapter describes: less code and less to get wrong, in exchange for being locked into Socket.IO's own client/server pairing rather than talking plain WebSocket.