skip to content

In Node.js, when a net.createServer TCP server accepts a connection, what do the Socket's 'data', 'end', 'error' and 'close' events each tell you?

level: juniorimportance: should knowfreq 40%

answer

  1. one net.Socket per connection
  2. chunks, not messages
  3. peer finished sending
  4. error is followed by close
  5. close carries hadError

basics

~20 s

Each connection arrives as a net.Socket: 'data' delivers a chunk of received bytes, 'end' means the peer stopped sending, 'error' reports a failure and is followed by 'close', and 'close' fires when the socket is fully shut.

solid answer

~40 s

`net.createServer()` calls its connection listener with one `net.Socket` per accepted connection. `'data'` hands you a `Buffer` (or a string after `setEncoding()`) holding whatever bytes the last read returned: a chunk, not a message. `'end'` means the peer signalled the end of transmission, so the readable side is finished; with the default `allowHalfOpen: false`, Node then ends your writable side once pending writes are flushed. `'error'` reports a failure such as `ECONNRESET`, and Node emits `'close'` directly after it. `'close'` fires when the socket is fully closed, and its `hadError` argument says whether an error caused it, which makes it the right place to release per-connection state. Always attach an `'error'` listener: an `'error'` event with no listener is thrown and the process exits.

code

javascript · 20 lines
javascript
import net from 'node:net';

const server = net.createServer((socket) => {
  const peer = `${socket.remoteAddress}:${socket.remotePort}`;

  socket.on('data', (chunk) => {
    console.log(`${peer} sent ${chunk.length} bytes`);
  });
  socket.on('end', () => {
    console.log(`${peer} finished sending`);
  });
  socket.on('error', (err) => {
    console.log(`${peer} error ${err.code}`);
  });
  socket.on('close', (hadError) => {
    console.log(`${peer} closed, hadError=${hadError}`);
  });
});

server.listen(7070);

go deeper

for a junior

Recall the four events with one sentence each: a chunk of bytes, the peer finished sending, a failure, fully closed. Mention that every socket needs an 'error' listener.

for a middle

Explain the two orderings, a clean end followed by close and an error followed directly by close, and what allowHalfOpen changes about who ends the writable side.

for a senior

Show where per-connection state is released and why: cleanup belongs in 'close' because 'end' is skipped on resets, and a missing 'error' listener turns one bad client into a process crash.

for a principal

Treat it as a team rule for raw socket code: every socket gets an 'error' listener and a 'close' cleanup path, enforced by review or a shared wrapper, because these bugs only show under real network faults.

## One socket per connection `net.createServer([options][, connectionListener])` from `node:net` creates a TCP server. Every time the operating system accepts a connection, the server emits `'connection'` and calls the listener with a fresh `net.Socket`. That socket is a **Duplex stream**: a readable side for bytes arriving from the client and a writable side for bytes you send back. Everything you learn about the connection reaches you as events on that one object, so knowing what each event means, and in which order they can arrive, is the whole lifecycle. On the client side the mirror image is `net.createConnection()` (also exported as `net.connect()`), whose socket emits `'connect'` once the connection is established, then `'ready'` immediately after. ## The four events that matter | Event | What it tells you | What to do there | |---|---|---| | `'data'` | A chunk of bytes arrived (`Buffer`, or a string after `socket.setEncoding()`) | Feed it to your message framer | | `'end'` | The peer signalled the end of transmission; nothing more will be read | Stop expecting input; finish any final reply | | `'error'` | Something failed, for example `ECONNRESET` when the peer reset the connection | Log it; Node closes the socket for you | | `'close'` | The socket is fully closed; `hadError` is `true` if an error caused it | Release timers, map entries and counters for this connection | Two details in that table trip people up: - **A `'data'` chunk is not a message.** It holds whatever one read from the kernel returned, so a single client write can be split across chunks and several writes can arrive in one. Framing is your job. - **Data emitted with no listener is lost.** The Node documentation states this plainly for `'data'`: attach the listener before you expect input. ## What a clean close and a failed one look like A connection that ends normally runs in this order: 1. Zero or more `'data'` events as the client sends. 2. `'end'` when the client finishes sending. 3. Node ends your writable side automatically (the default `allowHalfOpen: false`) after flushing what you queued. 4. `'close'` with `hadError` set to `false`. A connection that fails runs differently: 1. Possibly some `'data'` events. 2. `'error'`, carrying an `Error` with a `code` such as `ECONNRESET`. 3. `'close'` directly after, with `hadError` set to `true`. In the failing path `'end'` may never fire. That is why cleanup placed in an `'end'` handler leaks under real network faults while cleanup in `'close'` runs on every path. Calling `socket.destroy()` yourself also leads straight to `'close'` without an `'end'`. ## allowHalfOpen: who ends the writable side By default a `net.Socket` is created with `allowHalfOpen: false`. When the peer ends its side, Node sends its own end of transmission once pending writes are flushed, then destroys the socket. Pass `allowHalfOpen: true` to `net.createServer()` and Node leaves your writable side open after `'end'`: the socket is half-closed, unreadable but still writable, and you must call `socket.end()` yourself or the connection never finishes closing. That option exists for protocols where a client sends a whole request, signals it is done, and then waits for a long reply. What half-close means on the wire is a TCP topic; in Node it comes down to this one option and who calls `socket.end()`. ## Mistakes that crash or leak - **No `'error'` listener.** `net.Socket` is an `EventEmitter`, and an `'error'` event with no listener is thrown, prints a stack trace and exits the process. One client resetting its connection can take down the whole server. - **Cleanup in `'end'`.** It is skipped whenever the connection fails or is destroyed; use `'close'`. - **Treating `'end'` as closed.** After `'end'` the socket may still be flushing your writes; it is only gone at `'close'`. - **Expecting `'end'` with `allowHalfOpen: true` to close anything.** It will not; the server must end its side. - **Parsing each chunk as a message.** It works on a quiet local network and breaks under load or over slow links. A server that logs every lifecycle event is a quick way to watch these orderings yourself: compare a client that ends its side normally with one whose connection is reset, and the two sequences above appear in the log.

  • What changes if you create the server with allowHalfOpen: true?
    Node no longer ends your writable side when `'end'` fires. The socket stays half-closed: you cannot read any more, but you can keep writing, for example a final reply after the client signalled it had finished. You must then call `socket.end()` yourself, or the connection never finishes closing and `'close'` does not fire.
  • What is the difference between socket.end() and socket.destroy()?
    `socket.end()` half-closes politely: it flushes queued writes, then sends the end of transmission, and the peer may still send data until it ends too. `socket.destroy()` tears the connection down at once, discards anything still queued and leads to `'close'`; passing an error emits `'error'` first. `socket.resetAndDestroy()` goes further and closes with a TCP reset.

  • Each 'data' event carries exactly one message the client wrote.
  • 'end' means the socket is fully closed, so cleanup can run there.
  • An unhandled socket 'error' is only logged and the server keeps running.
  • 'close' only fires after a clean shutdown, so failed connections need separate cleanup.
  • After 'end', Node keeps the connection open until you call socket.end() yourself, even by default.