Practice & Assessment
Test your understanding of Building a WebSocket Server with Node.js
Multiple Choice Questions
6What does wss.clients contain in the ws Node.js package?
Why should you serialize a broadcast message before the client iteration loop?
What happens if you do not attach an error event listener to a ws client socket?
What is the safest way to pass authentication credentials when opening a WebSocket from the browser?
What should you do in the ws close handler to properly clean up room membership?
What is the difference between ws.close() and ws.terminate() in the ws package?
Coding Challenges
1Implement a Multi-Room Chat Server
Build a Node.js WebSocket server using the ws package that supports named rooms. It must handle four message types: { type: 'join', room: string } to join a room (and leave the current room if in one), { type: 'message', text: string } to broadcast to the current room excluding sender, { type: 'leave' } to leave the current room, and { type: 'list' } to receive back the list of active room names and their member counts. Clients not in a room should receive an error if they try to send a message. Include proper cleanup on disconnect. Input: WebSocket connections sending JSON messages. Output: JSON responses broadcast or sent per message type. Estimated time: 30 minutes.
Mini Project
Real-Time Chat Server with Rooms and Presence
Build a Node.js WebSocket server that handles: multi-room messaging with join/leave/message commands; per-room presence tracking (send a presence_update message to the room whenever membership changes, including the full list of current usernames); server-side ping every 30 seconds with connection termination if no pong within 5 seconds; JWT authentication in the query string with close code 4001 on failure; graceful shutdown on SIGTERM that closes all clients before process exit; and a simple HTTP GET /health endpoint that returns { status: 'ok', clients: N } using the same http server. Include a single HTML test client that connects, lets you join a room, and shows the presence list live.
