Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 133 ยท Networking and HTTP

TCP Servers and Clients with net

Build TCP servers and clients with the Node.js net module - sockets as duplex streams, echo and chat servers, message framing, half-close, idle timeouts, keep-alive and error handling.

Almost everything you do on the internet sits on top of TCP: web pages, email, databases, SSH. TCP gives two programs a reliable, ordered, two-way pipe of bytes. Node's built-in net module is the doorway to that pipe. http, tls, WebSockets and the database drivers you will use later are all built on it, so understanding net explains a lot about how they behave.

In this lesson you will write a TCP server and a client, see that a socket is just a duplex stream, learn why TCP has no concept of "messages" (and how to add them), and handle the half-closed connections, timeouts and errors that real networks produce. Everything runs on loopback (127.0.0.1), the address that never leaves your machine, so the examples run safely in the editor. Our sandbox has no external network, so a connection to a real remote host would fail.

A server and a client in one program

net.createServer(handler) creates a server; handler runs once for every client that connects and receives a socket. server.listen(port, host) starts accepting connections. On the other side, net.connect({ port, host }) opens a client socket.

For examples we always listen on port 0, which means "give me any free port", and read the real number from server.address().port. Hard-coded ports clash with other programs. We also always listen on 127.0.0.1 so nothing outside the machine can connect.

Node.js An echo server and a client

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 output in order; the steps of the conversation are visible. Three details deserve attention:

  • server.close() stops accepting new connections and fires 'close' only after every existing connection has ended. If a client stays connected, the server never closes and your program never exits. That is the most common reason a Node script "hangs".
  • client.end() means "I will send no more", it does not destroy the socket. The socket closes completely once both sides have ended.
  • data events deliver Buffer chunks (see Buffers). Call setEncoding('utf8') on the socket if you want strings.

Sockets are duplex streams

A net.Socket is a stream you can read and write, so everything from the Streams lessons applies: pipe, pipeline, async iteration, backpressure. The shortest possible echo server pipes the socket into itself.

Node.js Echo with pipe and async iteration

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.

for await (const chunk of client) ends when the server ends its side. Because pipe forwards the end-of-stream signal, the client's end() causes the server to end too. Notice also that we concatenate chunks into one string before printing: the number and size of chunks is not under your control, which brings us to the most important idea in this lesson.

TCP is a stream, not a list of messages

If a client calls write('one '), write('two '), write('three'), the server might get three data events, one event with all three, or any split in between. TCP only promises that the bytes arrive in order; it never promises where the boundaries between writes will be. A server that assumes "one data event is one message" will work in a quick local test and break under load.

You must therefore add framing: a rule that lets the receiver find message boundaries inside the byte stream. The two common rules:

  1. Delimiter-based. Messages end with a special byte, usually \n. Easy to debug (you can read it in a terminal), but the delimiter must never appear inside a message.
  2. Length-prefixed. Each message starts with its size in bytes, followed by that many bytes. Works for binary data; see Working with Binary Protocols.

For text, readline does newline framing for you: it turns the socket into an async iterable of complete lines, however the bytes were split.

Node.js Newline-delimited messages with readline

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 first write contains two full messages and half of a third; the second write completes it. The server still produces exactly three replies, because readline waits for each \n. This format (JSON objects separated by newlines) is often called NDJSON or JSON Lines, and it is a pragmatic choice for simple protocols.

Never assume one data event equals one message, and never assume one write on the sender equals one data on the receiver. Always frame your messages.

A chat server: many sockets, one program

A server can hold thousands of sockets. Keep them in a Set, add a socket when it connects, remove it on close, and loop over the set to broadcast. In the example two clients connect, one speaks, and both hear it. We wait on specific events rather than timers so that the output order is the same on every run.

Node.js A tiny broadcast chat server

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.

A real chat server would also assign names, handle commands and avoid echoing a message back to its sender. You will build exactly that kind of program in Project: Real-Time Chat Server.

Half-close: ending one direction

TCP connections have two independent directions. socket.end() closes only your sending side. The other side sees an 'end' event, but may still have things to send. By default Node closes the socket automatically as soon as the other side ends (the allowHalfOpen: false default). If you want a server that reads the whole request first and replies after the client has finished sending, set allowHalfOpen: true.

Node.js Reply after the client has half-closed

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 "send everything, signal the end, wait for the answer" pattern is how simple one-shot protocols (and old HTTP/1.0 clients) work. Without allowHalfOpen: true on the server, the socket would be closed when the client ended and the answer would never be sent.

Timeouts, keep-alive and connection limits

A socket can sit idle for a long time. Three tools help you manage that:

  • socket.setTimeout(ms) makes the socket emit 'timeout' after ms of inactivity. It does not close the socket for you: your handler decides, typically by calling socket.destroy() or socket.end().
  • socket.setKeepAlive(true, initialDelayMs) asks the operating system to send tiny probe packets on an idle connection, so that dead peers (a pulled network cable) are eventually detected and half-dead connections do not live for ever.
  • server.maxConnections rejects connections above a limit, and server.getConnections() counts the current ones.
Node.js Dropping an idle client

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.

For any server that faces the internet, idle timeouts are not optional: without them, a client that connects and never speaks holds a socket (and memory) for ever. This is the basis of the "slowloris" attack, and the reason http.Server has its own timeouts (see The http Module: Servers).

Error handling

Sockets are EventEmitters, so an 'error' event with no listener is thrown as an uncaught exception and kills the process (see Events and EventEmitter). Network errors are normal operation, not bugs: peers disappear, ports are closed, connections are reset. Always attach an 'error' listener to every socket, on both the server and the client side.

The first demonstration shows what happens when you forget. We find a free port by opening and closing a server, so nothing is listening there when the client connects.

Node.js Connecting to a closed port (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 process dies with an Error: connect ECONNREFUSED 127.0.0.1: followed by the random port number, and code: 'ECONNREFUSED' in the error details. The fix is to listen for 'error' and decide what to do: retry, report, give up.

Node.js Handling connection errors properly

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.

Common error codes: ECONNREFUSED (nothing listens there), ECONNRESET (the peer vanished abruptly), ETIMEDOUT (no answer), EPIPE (writing to a closed socket), EADDRINUSE (the port is taken when you call listen). Handle EADDRINUSE specially when you let users choose ports. See Errors and Error Handling for how Node reports system errors.

Performance and design notes

  • Backpressure. socket.write() returns false when its internal buffer is full. Pause the producer and resume on 'drain', or use pipeline, otherwise a slow client makes your server's memory grow. See pipeline and Backpressure.
  • Nagle's algorithm. By default small writes may be delayed and merged. For latency-sensitive protocols call socket.setNoDelay(true).
  • One request, one write. For small messages, build the whole frame in memory and call write once, rather than many tiny writes.
  • Limit your input. Cap the size of a line or frame. A client that sends a gigabyte without a newline must not be able to fill your memory.
  • Binding. Listening on 0.0.0.0 accepts connections from the whole network; 127.0.0.1 only from this machine. Choose deliberately.
  • Prefer higher layers. Write a raw TCP protocol when you need one (a database, a game, a custom device). For web traffic use http or WebSockets, which already solve framing, timeouts and security concerns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client writes 'one ', 'two ' and 'three' as three separate write() calls. What can the server rely on?

    TCP is a byte stream. Order is guaranteed, boundaries are not, which is why protocols need framing.
  2. 2. Why do the examples call server.listen(0, '127.0.0.1')?

    Port 0 asks the OS for a free port, which you read from server.address().port. The loopback address keeps the server private to the machine.
  3. 3. What does socket.end() do?

    end() is a half-close. The other side sees 'end', and the socket fully closes once both directions are finished.
  4. 4. What happens when a socket emits 'error' and no listener is attached?

    EventEmitter treats an unhandled 'error' event as fatal. Attach an error handler to every socket.
  5. 5. What does socket.setTimeout(30) do when the socket is idle for 30 ms?

    The timeout only emits an event. You must call end() or destroy() yourself if you want the connection closed.

Summary

  • net.createServer(handler) plus listen(0, '127.0.0.1') creates a server; net.connect() creates a client. Read the real port from server.address().port.
  • A socket is a duplex stream: use data events, pipe, pipeline or for await.
  • TCP delivers a byte stream, so add framing (newline-delimited or length-prefixed) to find message boundaries.
  • end() is a half-close; use allowHalfOpen for servers that reply after the client finishes sending. server.close() waits for open connections.
  • Set idle timeouts, optionally keep-alive, and always attach 'error' listeners; know ECONNREFUSED, ECONNRESET and EADDRINUSE.
  • Respect backpressure and limit input sizes.

Next: The http Module: Servers