How does a chat application use WebSockets?

Answer

A WebSocket-based chat application works as follows: (1) Each user connects to the WebSocket server on page load, creating a persistent connection; (2) The server maintains a map of userId → WebSocket connection; (3) When User A sends a message, their browser sends it to the server via ws.send(JSON.stringify({ to: 'UserB', text: 'Hello' })); (4) The server receives the message, looks up User B's connection, and calls connectionB.send(...) to deliver it; (5) User B's browser receives the message event and updates the UI. For group chats, the server iterates all connections in a room and sends to each. The key advantage: message delivery is near-instant (milliseconds) without any polling — messages "push" directly to connected users the moment they're sent.