← Back to Node.js, page 5

nodejs-0085 · Medium mid

How do you build a TCP server and client with the net module, and what events matter?

net.createServer gives a handler that receives a socket for each client. A socket is a duplex stream: read with the 'data' event or pipe, write with socket.write. Key events are 'connection', 'data', 'end' (the other side finished sending), 'close' and 'error'. TCP is a byte stream, so message boundaries are not preserved.

Full answer

net is the low-level API under http and many databases. A TCP connection is a reliable, ordered, two-way stream of bytes.

Server side:

  • const server = net.createServer((socket) => { ... }); server.listen(port, host).
  • Each socket is a Duplex stream. socket.setEncoding('utf8') turns chunks into strings. socket.pipe(socket) makes an echo server.
  • server.close() stops accepting new connections and calls back when all existing ones end.
  • server.address() gives the actual port (use listen(0) in tests).

Client side: net.connect({ port, host }) or net.createConnection returns a socket. 'connect' fires when the connection is ready.

Events and behaviours:

  • 'data': a chunk arrived. The chunk size is not tied to how the other side wrote. Two writes can arrive as one chunk, and one write as several.
  • 'end': the other side called end() (half-close). By default Node then closes your side as well (allowHalfOpen: false).
  • 'close': the connection is fully closed (hadError says whether an error caused it).
  • 'error': always attach a handler. A reset by the peer (ECONNRESET) is common and, unhandled, crashes the process.
  • 'timeout' with socket.setTimeout(ms): fires when idle. Then destroy the socket yourself.
  • Backpressure: socket.write returns false when the buffer is full. Wait for 'drain'.
  • socket.setKeepAlive and setNoDelay (disables Nagle's algorithm, useful for small latency-sensitive messages).

Since sockets are streams, pipeline, transforms and async iteration all work. Protocol design is your job: choose delimiters or length prefixes (see the framing question).

javascript
const net = require('node:net');

const server = net.createServer((socket) => {
  socket.setEncoding('utf8');
  socket.on('error', (err) => console.log('server socket error:', err.code));
  socket.on('data', (text) => socket.write('echo: ' + text.toUpperCase()));
  socket.on('end', () => console.log('server: client finished sending'));
  socket.on('close', () => console.log('server: connection closed'));
});

server.listen(0, '127.0.0.1', () => {
  const { port } = server.address();
  const client = net.connect({ port, host: '127.0.0.1' });
  client.setEncoding('utf8');

  client.on('connect', () => {
    console.log('client: connected');
    client.write('hello node');
  });
  client.on('data', (reply) => {
    console.log('client received:', reply);
    client.end(); // we are done: send FIN
  });
  client.on('close', () => {
    console.log('client: closed');
    server.close(() => console.log('server: stopped accepting and all connections are gone'));
  });
  client.on('error', (err) => console.log('client error:', err.code));
});

The server listens on port 0, so the system chooses a free port, and the order of the events shows the life of one connection. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): client: connected client received: echo: HELLO NODE server: client finished sending server: connection closed client: closed server: stopped accepting and all connections are gone

Key points

  • Each connection gives a duplex socket stream.
  • 'end' means the peer finished. 'close' means fully closed.
  • Always handle 'error' on sockets.
  • TCP does not keep message boundaries.

Common mistakes

  • Assuming one write on the client equals one 'data' event on the server.
  • Not handling 'error', so a reset connection crashes the process.
  • Never closing idle sockets.
  • Ignoring backpressure when sending large data.

Follow-ups

  • What is Nagle's algorithm and when do you disable it?
  • How does allowHalfOpen change the behaviour?
  • How would you limit the number of connections?

Tips

  • Say 'TCP is a stream, not messages' early.
  • Know the difference between end and close.
  • Mention listen(0) for tests.