Challenge 1: Build an Echo Server — Possible Solution ==================================================================== import { WebSocketServer } from "ws"; const wss = new WebSocketServer({ port: 8080 }); wss.on("connection", (socket) => { console.log("A client connected."); socket.on("message", (data) => { const text = data.toString(); console.log("Received:", text); socket.send(text); // send it straight back to THIS client only }); socket.on("close", () => { console.log("A client disconnected."); }); socket.on("error", (err) => { console.error("Socket error:", err); }); }); console.log("Echo server listening on port 8080"); WHY THIS WORKS -------------- - new WebSocketServer({ port: 8080 }) starts listening for incoming WebSocket handshakes on that port — the library takes care of the entire Chapter 2 handshake process (Upgrade headers, Sec-WebSocket-Key hashing, responding 101 Switching Protocols) automatically. - The "connection" callback receives a fresh "socket" object for EACH client — calling socket.send(text) inside THIS callback sends the reply back to only the one client whose message triggered it, since "socket" here is scoped to that specific connection, not shared across clients. - data.toString() is necessary because "message" events deliver a Buffer by default, not a plain string — sending it back with socket.send(text) after converting keeps the echoed reply as readable text rather than raw binary. - Handling "close" and "error" isn't strictly required for the echo behavior itself, but it's included here because a server that never logs disconnects or errors is much harder to debug once something actually goes wrong — a habit worth building from the first server you write.