Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 133 ยท Projects

Project: Real-Time Chat Server

Build a multi-room chat server in Node.js with the net module. Line protocol, nicknames, rooms, history, slow-client protection and loopback clients, built in stages and tested.

A chat server is the classic first real-time project. Many clients stay connected at the same time, a message from one must reach all the others within a moment, and people come and go without warning. Everything that makes Node.js good at networking shows up here: one process, one thread, thousands of open sockets, and no waiting around for any of them.

In this project you build a small multi-room chat server on top of the net module you met in TCP servers and clients. It has nicknames, rooms, a short history that new arrivals see, and protection against clients that misbehave. You will build it in stages: first the chat logic with no network at all, then the TCP layer, then the failure cases that separate a toy from a server. Every stage runs here in the editor, because the server and its clients live in the same program and talk over the loopback address.

Plan: separate the chat from the wire

The most important design decision is to keep two jobs apart.

  • The hub knows about users, rooms, nicknames and history. It receives lines of text and decides who should be sent what. It knows nothing about sockets.
  • The server knows about sockets. It turns each connection into lines, hands them to the hub, and writes whatever the hub wants to send back.

The link between them is one function per user, send(line). The hub calls it, and does not care whether it writes to a socket, an array in a test, or a WebSocket. This is the same idea as the layers in project structure and architecture, and it pays off immediately: the hub can be tested with plain arrays, fast and without any ports.

The protocol is deliberately simple: one message per line, UTF-8 text, ending in \n. A line that starts with / is a command, anything else is a message to your current room.

Line Meaning
/nick name Change your nickname (2-16 letters, digits or _)
/join room Move to a room (it is created on first use)
/rooms List rooms and how many people are in each
/who List the people in your room
/quit Say goodbye and disconnect
anything else Send the text to everyone in your room

Lines from the server start with * for notices, ! for errors, [#room] nick: for chat messages and (earlier) for replayed history. A real protocol would use JSON or a length prefix (see binary protocols), but plain lines are easy to read in a log and to try with a tool such as nc or telnet.

Stage 1: the hub, without a network

The hub is a class with three public methods: connect(send) registers a user and returns an id, handle(id, line) processes one line from that user, and disconnect(id) removes them. Everything else uses private fields and methods (#name), so callers cannot reach into the state.

The tests below create "fake clients": an inbox array that collects whatever the hub sends. First the program prints a tiny conversation, then it runs four checks written with node:assert.

Node.js Stage 1: the chat hub and its tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the conversation at the top. Ben sees the welcome, the #lobby notice, his own nickname change, Ann's message and the /who answer. Notice what he does not see: the announcement that guest2 joined. People are told about other people entering, never about themselves, which is what the except argument of #announce does.

A few design points hide in this small class:

  • History is capped. slice(-this.#historySize) keeps only the newest lines, so memory per room is bounded no matter how long the room lives. Without a cap, a room is a memory leak that grows with every message.
  • Validation is done once, in the hub. Nicknames and room names are checked with strict regular expressions. A nickname that could contain spaces or control characters would let a user fake someone else's lines in everybody's output.
  • Nickname comparison ignores case, so Ann and ann cannot both exist and impersonate each other.
  • handle returns { close } instead of closing anything. The hub does not own the connection, so it only says what should happen and lets the server do it.

Write tests for the core before you add the network. A test that needs only arrays runs in a millisecond and fails with a precise message. The same checks through real sockets are slower and fail with "timed out" when anything is wrong. See assertions and the node:test runner for the full toolbox.

Stage 2: the TCP server

Now the wire. A TCP socket delivers a stream of bytes, not messages. One data event might hold half a line, or three lines and the start of a fourth. Splitting the stream into lines is exactly the job of readline, so the server wraps each socket in a readline interface and reacts to its line events. This is the same "carry the unfinished part of a line to the next chunk" problem from stream patterns, solved for you.

The server function has three responsibilities per connection:

  1. Build a send function that writes a line to this socket.
  2. Register the user with the hub and feed every incoming line to hub.handle.
  3. Tell the hub when the socket closes, so the user disappears from their room.
NODE
function startChatServer(hub) {
  const server = net.createServer((socket) => {
    socket.setEncoding('utf8');
    const send = (line) => { /* guard, then socket.write(line + '\n') */ };
    const id = hub.connect(send);
    const lines = readline.createInterface({ input: socket, crlfDelay: Infinity });
    lines.on('line', (line) => { if (hub.handle(id, line).close) socket.end(); });
    socket.on('error', () => {});
    socket.on('close', () => hub.disconnect(id));
  });
  // ...
}

The real version is in the next example. Two details deserve a closer look. crlfDelay: Infinity makes readline treat \r\n as one line break even if the two characters arrive in different chunks, which telnet-style clients on Windows send. And socket.end() after /quit sends a FIN packet after flushing pending writes, so the client still receives the final * bye line. Calling socket.destroy() there would cut the connection off and could lose it.

The next program contains everything: the hub, the server, a small client helper and a scripted conversation among three people. The helper connectClient returns an object with send(text) and expect(text), where expect waits until a line containing the text has arrived. Waiting for specific lines, instead of sleeping for a fixed time, is what keeps the output identical on every run.

Node.js Stage 2: server, clients and a conversation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Follow the three transcripts and you can see the whole design working:

  • Ann and Ben talk in #lobby, then both /join dev. Ben is told ann left #dev after Ann quits.
  • Carol arrives later. She joins #lobby first (the default), then moves to #dev and receives the last two lines of its history, yes, just us and quiet now. The first message, anyone here?, was pushed out by the cap of two.
  • /rooms shows #dev (2): Ben and Carol. Ann is gone, and nobody is left in the lobby, so the empty room does not appear. Rooms exist only while someone is in them, because they are derived from the users rather than stored.
  • Closing works in order: the clients end their sockets, the server's close handlers remove the users, and server.close() finishes once all connections are gone. A server that is not closed would keep the program alive forever.

The loopback trick (listen on 127.0.0.1 with port 0, read the real port from server.address(), connect from the same program) is how every networking example in this track stays self-contained. Port 0 asks the operating system for any free port, so it never collides with anything.

Stage 3: what happens when a client misbehaves

Real clients disconnect rudely: a laptop lid closes, a phone leaves Wi-Fi, a process is killed. In those cases the TCP connection is reset instead of closed politely, and the socket emits an 'error' event. The rule you learned in events applies with full force: an 'error' event with no listener is thrown, and an uncaught exception ends the process. One rude client could take down the whole chat for everybody.

Here is a server without an error listener. The client connects, sends one line, and then resets the connection the way a crash would (resetAndDestroy() sends a TCP RST).

Node.js A reset connection crashes the server (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The server logs got hello and then dies with Unhandled 'error' event and Error: read ECONNRESET. The stack trace points inside Node (node:events, node:internal/stream_base_commons), not at your code, which is typical for network errors: the failure happened in the socket, not in a line you wrote. The fix is a single listener. It does not need to do much, because after an 'error' the socket is destroyed and a 'close' event always follows, which is where you clean up.

Node.js The same reset, handled

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This is the version the chat server uses: socket.on('error', () => {}) plus cleanup in 'close'. See errors for the general rules about which failures to handle and which to let crash.

Stage 4: hardening checklist

The server above is correct, but a server on the internet needs a few more protections. The first is already in the code, the others are small additions you can try as an exercise.

  • Slow readers (done). socket.write() buffers data in memory when the client does not read fast enough. The send function checks socket.writableLength and destroys any client with more than 16 KB queued. Without this, one client that never reads makes the server's memory grow with every message broadcast to it. This is backpressure seen from the other side: for a broadcast you cannot slow the sender down, so you drop the slow receiver.
  • Huge lines. readline buffers a line until it sees \n. A client that sends gigabytes without a newline fills memory. Add a counter of bytes since the last newline (or use socket.bytesRead limits) and destroy offenders. The hub's 200-character limit only applies after the whole line has been read.
  • Idle connections. Call socket.setTimeout(60_000) and destroy the socket on the 'timeout' event, or require a ping command.
  • Flooding. Count messages per user per second and refuse extras. A rate limiter belongs next to the hub's handle method.
  • Too many connections. server.maxConnections makes the server refuse new sockets over a limit.
  • Shutdown. On SIGTERM, tell users * server is shutting down, call server.close(), end each socket, and exit when the last one is gone (see process and deployment).

Variants and scaling

Nothing in the hub depends on TCP. To serve browsers, keep the hub and replace the server:

  • WebSocket (WebSockets): each connection's message event calls hub.handle, and send calls ws.send. Real chat clients in a web page use this.
  • Server-Sent Events (SSE): send writes data: ... frames to a long-lived HTTP response, and messages from the browser arrive as ordinary POST requests.
JavaScript
// Read-only sketch: the same hub behind the ws package (not installed in our editor).
import { WebSocketServer } from 'ws';

const hub = new ChatHub();
const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws) => {
  const id = hub.connect((line) => ws.send(line));
  ws.on('message', (data) => {
    if (hub.handle(id, data.toString()).close) ws.close();
  });
  ws.on('close', () => hub.disconnect(id));
});

One process holds the whole state in memory, so one process is also the limit. When you need several servers (see cluster and scaling and scalability patterns), users in the same room may be connected to different processes. The usual answer is a shared message bus (Redis pub/sub, NATS) that every process publishes room messages to and subscribes from. The hub's #announce becomes "publish to the bus", and a subscriber delivers to the local members. Because the hub already isolates delivery behind send, that change is local.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the chat hub receive a send function instead of a socket?

    The hub only needs "a way to deliver one line to this user". Keeping sockets out of it makes it testable with arrays and reusable behind other transports.
  2. 2. What problem does wrapping a TCP socket in readline solve?

    TCP is a byte stream with no message boundaries. A data event can hold half a line or several lines, and readline reassembles them into line events.
  3. 3. What happens if a socket emits 'error' and no listener is registered?

    EventEmitter throws an unhandled error event. For sockets this means one reset connection can crash the entire server unless you add an error listener.
  4. 4. Why does the send function destroy a socket whose writableLength is large?

    A broadcast cannot wait for each reader, so data piles up in memory for slow clients. Dropping them keeps server memory bounded.
  5. 5. Why does the server call socket.end() rather than socket.destroy() after /quit?

    end() flushes queued writes and then closes the sending side. destroy() tears the connection down immediately and may lose data that was not sent yet.

Summary

  • Split the project into a transport-free hub (users, rooms, history) and a thin TCP layer that turns sockets into lines.
  • A line protocol is easy to read and debug; readline handles chunk boundaries for you.
  • Validate nicknames and room names strictly, cap history and message length, and compare nicknames case-insensitively.
  • Always add socket.on('error'), and clean up in 'close', which follows every error.
  • Protect the server from slow readers, endless lines, idle sockets and floods.
  • Use port 0 on 127.0.0.1 and expect-style helpers so networked examples are deterministic.
  • The hub can sit behind WebSockets or SSE unchanged, and scales out through a shared message bus.

Next: Project: Streaming Log Processor