Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 79 ยท How the Web Works and Real-World Projects

Project: A TCP Chat Server and Client

Build a chat server on raw TCP sockets: a line-based protocol, nicknames, broadcast, message framing on a byte stream and robust handling of bad clients.

A chat room is the classic first network program, because it forces you to face the questions that every real protocol answers: how do the two sides agree on what a message looks like, how does the server keep track of many connections at once, and what happens when a client misbehaves or disappears? In this project you build a complete chat server and client on raw TCP sockets, with nicknames, broadcast messages and a small command set, and you test it live over the loopback interface.

You should know what a socket is from the socket programming lesson. The key fact from that lesson is the starting point here: TCP is a byte stream, not a message service. If a client sends two messages, the server may receive them in one piece, or one message may arrive in three pieces. The server must put the boundaries back. That job is called framing, and it is the heart of this project.

Designing the protocol

Before any code, decide what goes over the wire. Text protocols are easy to debug (you can even test them with a plain telnet or nc session), so we use one message per line, ending in \n.

Direction Line Meaning
client to server NICK <name> choose a nickname (2 to 16 letters, digits or _)
client to server MSG <text> say something to everyone else
client to server WHO list the people in the room
client to server QUIT leave politely
server to client HELLO ... greeting when you connect
server to client OK ... / ERR ... success or failure of the last command
server to client FROM <nick> <text> a message from someone else
server to client JOIN <nick> / LEAVE <nick> people arriving and leaving
server to client USERS a,b,c the reply to WHO
server to client BYE goodbye after QUIT

Every line starts with an uppercase verb, followed by an optional argument. This is the same design as SMTP or FTP, and it keeps the parser trivial: split at the first space.

sequenceDiagram
    participant A as Alice
    participant S as Server
    participant B as Bob
    A->>S: connect
    S-->>A: HELLO
    A->>S: NICK alice
    S-->>A: OK welcome alice
    B->>S: NICK bob
    S-->>B: OK welcome bob
    S-->>A: JOIN bob
    B->>S: MSG hi
    S-->>A: FROM bob hi
    B->>S: QUIT
    S-->>B: BYE
    S-->>A: LEAVE bob

A typical session. The server answers the sender and informs everyone else (the broadcast).

Framing: turning a stream back into lines

TCP guarantees that bytes arrive complete and in order. It does not guarantee that one write() on one side equals one data event on the other. The network may split data into several segments, and the operating system may merge small writes. The fix is a buffer: append every chunk, then cut off complete lines as long as there is a newline in the buffer. Whatever is left (an incomplete line) stays in the buffer until the next chunk arrives.

The same approach protects against two kinds of attack. A client that never sends a newline would make the buffer grow forever, so the buffer has a maximum length; if it is exceeded, the connection is cut. Windows-style \r\n endings are tolerated by removing a trailing \r.

Node.js Step 1: a line splitter and the framing problem

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.

All three ways of cutting the same 34 bytes produce the same three lines, which is the property a stream protocol needs: the result must not depend on how the network chopped up the data. Programs that skip this step usually appear to work on localhost (where chunks are small and rarely split) and fail on real networks.

Line-based framing is only one choice. Binary protocols often use a length prefix (a 4-byte number saying how many bytes follow), which is faster to parse and can carry arbitrary bytes, including newlines. HTTP uses a mix: header lines end with \r\n, and the body length comes from a Content-Length header or from chunk sizes.

The server

The server keeps one record per connection: the socket, the nickname (or null until the client picks one) and the input buffer. All records live in a Set, so broadcasting is a loop over the set.

Look at the main decisions in the code below.

  • The data handler is the line splitter from Step 1, inline. socket.setEncoding('utf8') matters: it makes Node decode bytes with a decoder that remembers an incomplete multi-byte character between chunks, so an รฉ cut in half by the network does not turn into garbage.
  • handle() is a tiny command dispatcher. It rejects every command except NICK until the client has a nickname, and it validates the nickname with a regular expression to stop empty names, spaces and control characters.
  • broadcast() sends a line to every named client except the sender. The sender gets an OK or an ERR instead of an echo of its own message.
  • leave() runs on the socket's close event, which fires both after a polite QUIT and when the connection simply drops, so the room is always told. It checks clients.delete(...) first, so it can never announce the same departure twice.
  • Errors on a socket (like a reset by the peer) are swallowed with an empty error handler. Without a handler, Node would treat the error as fatal and crash the whole server because of one bad client.

The client in this lesson is a scripted test client, which lets the example run unattended. Two helper methods make scripts readable: send(text) writes to the socket and records it, and read() returns a promise for the next line the server sends.

Node.js Step 2: a chat server and two clients

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 transcript from top to bottom and you can follow the protocol exactly. Note that Alice gets JOIN bob only after Bob finishes his NICK, that Bob never receives his own message back, and that LEAVE bob is produced by the server, not by Bob: Bob only said QUIT.

Surviving real-world clients

A server that handles only polite clients is not a server, it is a demo. The next run uses the same server code and attacks it in the ways real clients do:

  1. A command split across writes (NI, CK ali, ce\r\n).
  2. Commands in the wrong order and a duplicate nickname.
  3. Two messages in one write.
  4. Non-ASCII text cut inside a character.
  5. Unknown and empty commands.
  6. A client that sends an enormous line with no newline.
  7. A client that disappears without saying goodbye.
Node.js Step 3: bad clients

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.

Every scenario ends with the server still running and with the other users informed. That is the standard to aim for: a network service must never trust its peers, never crash because of their input, and always clean up their state when they leave.

A real terminal client

The scripted client verifies the protocol, but a person wants to type. A terminal client needs only two jobs: copy lines from the keyboard to the socket and lines from the socket to the screen. Node's readline gives you the keyboard side. Save this as client.js and run it against the server code from Step 2 on a real machine, after changing its server.listen(0, '127.0.0.1') to server.listen(4000). It is read-only here, because the runner cannot read your keyboard:

JavaScript
import net from 'node:net';
import readline from 'node:readline';

const [host = '127.0.0.1', port = '4000', nick = 'guest'] = process.argv.slice(2);
const socket = net.connect(Number(port), host);
socket.setEncoding('utf8');

socket.once('connect', () => socket.write(`NICK ${nick}\n`));
socket.on('data', (chunk) => process.stdout.write(chunk));
socket.on('close', () => { console.log('disconnected'); process.exit(0); });

const input = readline.createInterface({ input: process.stdin });
input.on('line', (line) => socket.write(line.startsWith('/') ? `${line.slice(1)}\n` : `MSG ${line}\n`));

Typing hello sends MSG hello, while typing /WHO sends WHO. To test the server from outside Node, use nc 127.0.0.1 4000 and type the protocol lines yourself; that is the advantage of a text protocol. (This client prints raw lines; a polished client would reformat FROM bob hi as bob: hi.)

Ideas to extend it

  • Private messages. Add TO <nick> <text> and deliver only to that user, replying with an ERR if the nickname is unknown.
  • Rooms. Add JOIN #room and store the room name in each client record, then broadcast only inside the room.
  • Rate limiting. Count messages per client per second and warn or disconnect spammers (compare the token bucket in Multicast and QoS).
  • Idle timeouts. Use socket.setTimeout() to disconnect clients that say nothing for several minutes.
  • A binary protocol. Replace lines with a 2-byte length prefix and compare the code.
  • Encryption. Wrap the server in tls.createServer, so the same protocol is protected like HTTPS.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client calls write() twice with two short messages. What may the server's 'data' handler receive?

    TCP is a byte stream with no message boundaries. Chunk sizes depend on segmentation and buffering, so the server must rebuild messages itself, for example by splitting on newlines.
  2. 2. What should the server do with the part of the buffer after the last newline?

    That text is an incomplete line. The next chunk will contain the rest of it, so the buffer must keep it.
  3. 3. Why does the server limit the length of the buffer?

    Without a limit, an attacker could send endless data without a newline and exhaust memory. Limits on line length, message size and number of connections are basic hardening.
  4. 4. Why is there an empty 'error' listener on every socket?

    In Node, an 'error' event with no listener is thrown as an exception. A reset connection from one client must not stop the whole server; the 'close' handler does the clean-up.
  5. 5. Why call socket.setEncoding('utf8') instead of converting each chunk with chunk.toString()?

    The stream decoder keeps an incomplete character until the remaining bytes arrive. Converting chunks separately would turn a split character into replacement characters.

Summary

  • A chat protocol is a set of verbs and replies. Line-based text is easy to read, test with nc and extend.
  • TCP is a byte stream. Servers must frame it: append chunks to a buffer, cut complete lines, keep the remainder, and enforce a maximum length.
  • The server keeps a record per connection, dispatches commands, broadcasts to everyone except the sender and cleans up on close.
  • Treat every client as hostile or broken: validate nicknames and commands, handle partial lines, oversized input and abrupt disconnects, and swallow per-socket errors.
  • A scripted client over loopback makes the protocol testable; a terminal client only copies lines between keyboard and socket.

Next, apply the same skills to the protocol that runs the web: a tiny HTTP server built from raw TCP.