A real-time WebSocket chat server with named rooms and multi-client support. I wrote this code to understand how persistent connections work — how a server keeps multiple clients alive simultaneously, routes messages between them, and handles disconnects cleanly.
WebSocket keeps a persistent connection open between client and server. When a message comes in, the server parses it, looks up the room, iterates the connected clients, checks each connection is still open, and sends. The sender is excluded to prevent echo.
{ "type": "setName", "username": "simon" }{ "type": "join", "room": "backend" }{ "type": "message", "text": "hello" }{ "type": "info", "message": "Joined room: backend" }
{ "type": "message", "from": "simon", "room": "backend", "text": "hello" }
{ "type": "error", "message": "Invalid message format" }npm install
node index.jsConnect with any WebSocket client on ws://localhost:3002
Node.js · Express · ws