Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns

The Node.js net.Socket class

Reference for net.Socket in Node.js: the duplex stream behind TCP and IPC connections, with its events, methods, address properties, timeouts and byte counters.

net.Socket is the object that represents one end of a TCP connection or local IPC channel. It is a duplex stream: you read the bytes the peer sends (as 'data' events, with for await, or through pipe()) and write bytes with write() and end(). Everything you know about streams applies, including backpressure and pipeline().

You rarely construct a socket yourself. Clients get one from net.createConnection(), and servers receive one per client in the 'connection' event of net.Server.

NODE
import net from 'node:net';

const socket = net.createConnection({ port: 3000, host: '127.0.0.1' });
socket.setEncoding('utf8');
socket.on('data', (text) => console.log(text));
socket.end('request\n');

Try it

Node.js Addresses, byte counters and events

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.

Node.js Idle timeout and destroy

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.

Syntax

NODE
class net.Socket extends stream.Duplex
new net.Socket(options?: { fd?, allowHalfOpen?, readable?, writable?, signal? })

Events

Event Fires when
'connect' the connection is established (client side).
'ready' the socket is ready to use, right after 'connect'.
'data' bytes (Buffer, or string after setEncoding()) arrive.
'end' the peer has finished sending (FIN received).
'finish' all your writes have been flushed after end().
'close' the socket is fully closed; the argument tells whether an error occurred.
'error' a failure such as ECONNRESET or EPIPE; 'close' follows.
'timeout' the socket was idle for the configured time.
'drain' the write buffer has emptied after write() returned false.
'lookup' the host name was resolved, before connecting.

Methods

Name Description
write(data, encoding?, callback?) Sends data; returns false when you should wait for 'drain'.
end(data?) Sends the final data and a FIN; the socket can still read.
destroy(error?) Closes immediately and discards pending writes.
setEncoding(enc) Delivers strings instead of buffers.
setTimeout(ms, listener?) Reports idleness; 0 disables it.
setNoDelay(flag) Disables Nagle's algorithm for low latency.
setKeepAlive(flag, delay) Enables TCP keep-alive probes.
pause(), resume() Control reading.
ref(), unref() Whether the socket keeps the process alive.
address() Local { address, family, port }.

Properties: localAddress, localPort, remoteAddress, remotePort, remoteFamily, bytesRead, bytesWritten, bufferSize (deprecated, use writableLength), connecting, pending, readyState ('opening', 'open', 'readOnly', 'writeOnly'), destroyed, timeout.

Errors and edge cases: writing after end() emits ERR_STREAM_WRITE_AFTER_END; writing to a socket the peer has reset emits EPIPE or ECONNRESET through 'error'.

Usage notes

  • end() is polite, destroy() is abrupt. end() flushes buffered data and sends a FIN. destroy() drops everything; the peer may see a reset.
  • Half-close. With the default allowHalfOpen: false, receiving 'end' automatically ends your side too. Set it to true for protocols that reply after the request ends.
  • 'end' is not 'close'. 'end' means no more incoming data; 'close' means the handle is released. Do cleanup in 'close'.
  • Chunks are arbitrary. Never assume one 'data' equals one message. Accumulate and split yourself, or read lines with readline.
  • setTimeout() never closes anything. Always handle 'timeout'.
  • remoteAddress can be undefined after the socket has been destroyed; read it early if you log it.
  • IPv4-mapped addresses. A server bound to :: may report clients as ::ffff:127.0.0.1.
  • Backpressure. A fast producer must honor the false return of write(); stream.pipeline() does this for you.