On this page

C

net.Socket

History
class net.Socket extends stream.Duplex

This class is an abstraction of a TCP socket or a streaming IPC endpoint (uses named pipes on Windows, and Unix domain sockets otherwise). It is also an EventEmitter.

A net.Socket can be created by the user and used directly to interact with a server. For example, it is returned by net.createConnection(), so the user can use it to talk to the server.

It can also be created by Node.js and passed to the user when a connection is received. For example, it is passed to the listeners of a 'connection' event emitted on a net.Server, so the user can use it to interact with the client.

A connected TCP net.Socket can be moved to another thread by listing it in the transferList of a worker_threads postMessage() call. After the transfer, the source socket is destroyed on the sending thread (further use fails with ERR_STREAM_DESTROYED rather than silently dropping data), and the socket continues to work on the receiving thread. This makes it possible to accept connections on one thread and distribute them across a pool of worker threads, for example to build a node:cluster-like model on top of worker threads.

The socket must be a freshly accepted or created TCP connection: it must still be attached to a live handle, must not be connecting or destroyed, and must not have started reading or have buffered data. Otherwise postMessage() throws ERR_WORKER_HANDLE_NOT_TRANSFERABLE. Only TCP sockets are supported.

const net = require('node:net');
const { Worker } = require('node:worker_threads');

// worker.js receives `{ socket }` messages and handles each connection.
const worker = new Worker('./worker.js');

const server = net.createServer((socket) => {
  // Hand the freshly accepted connection off to the worker thread.
  worker.postMessage({ socket }, [socket]);
});
server.listen(8000);

A listening net.Server can be transferred the same way, which moves the listening socket itself (and its pending accept queue) to the receiving thread.

new net.Socket(options?): net.Socket
Attributes
options:Object
Available options are:
allowHalfOpen?:boolean
If set to false, then the socket will automatically end the writable side when the readable side ends. See net.createServer() and the 'end' event for details. Default: false.
blockList:net.BlockList
blockList can be used for disabling outbound access to specific IP addresses, IP ranges, or IP subnets.
If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created.
If specified, wrap around the bound socket from a BoundSocket. A subsequent socket.connect() uses the bound socket as the connection's source binding (honoring the bound local address and port). Adoption consumes the bound socket (see ownership transfer).
keepAlive?:boolean
If set to true, it enables keep-alive functionality on the socket immediately after the connection is established, similarly on what is done in socket.setKeepAlive(). Default: false.
keepAliveInitialDelay?:number
If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. Default: 0.
noDelay?:boolean
If set to true, it disables the use of Nagle's algorithm immediately after the socket is established. Default: false.
onread:Object
If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. This will cause the streaming functionality to not provide any data. The socket will emit events like 'error', 'end', and 'close' as usual. Methods like pause() and resume() will also behave as expected.
Either a reusable chunk of memory to use for storing incoming data or a function that returns such.
callback:Function
This function is called for every chunk of incoming data. Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. Return false from this function to implicitly pause() the socket. This function will be executed in the global context.
readable?:boolean
Allow reads on the socket when an fd is passed, otherwise ignored. Default: false.
An Abort signal that may be used to destroy the socket.
typeOfService:number
The initial Type of Service (TOS) value.
writable?:boolean
Allow writes on the socket when an fd is passed, otherwise ignored. Default: false.
Returns:net.Socket

Creates a new socket object.

The newly created socket can be either a TCP socket or a streaming IPC endpoint, depending on what it connect() to.

E

close

History
Attributes
hadError:boolean
true if the socket had a transmission error.

Emitted once the socket is fully closed. The argument hadError is a boolean which says if the socket was closed due to a transmission error.

E

connect

History

Emitted when a socket connection is successfully established. See net.createConnection().

E

connectionAttempt

History
Attributes
The IP which the socket is attempting to connect to.
port:number
The port which the socket is attempting to connect to.
family:number
The family of the IP. It can be 6 for IPv6 or 4 for IPv4.

Emitted when a new connection attempt is started. This may be emitted multiple times if the family autoselection algorithm is enabled in socket.connect(options).

E

connectionAttemptFailed

History
Attributes
The IP which the socket attempted to connect to.
port:number
The port which the socket attempted to connect to.
family:number
The family of the IP. It can be 6 for IPv6 or 4 for IPv4.
error:Error
The error associated with the failure.

Emitted when a connection attempt failed. This may be emitted multiple times if the family autoselection algorithm is enabled in socket.connect(options).

E

connectionAttemptTimeout

History
Attributes
The IP which the socket attempted to connect to.
port:number
The port which the socket attempted to connect to.
family:number
The family of the IP. It can be 6 for IPv6 or 4 for IPv4.

Emitted when a connection attempt timed out. This is only emitted (and may be emitted multiple times) if the family autoselection algorithm is enabled in socket.connect(options).

E

data

History
Type:Buffer | string

Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding().

The data will be lost if there is no listener when a Socket emits a 'data' event.

E

drain

History

Emitted when the write buffer becomes empty. Can be used to throttle uploads.

See also: the return values of socket.write().

E

end

History

Emitted when the other end of the socket signals the end of transmission, thus ending the readable side of the socket.

By default (allowHalfOpen is false) the socket will send an end of transmission packet back and destroy its file descriptor once it has written out its pending write queue. However, if allowHalfOpen is set to true, the socket will not automatically end() its writable side, allowing the user to write arbitrary amounts of data. The user must call end() explicitly to close the connection (i.e. sending a FIN packet back).

E

error

History
Type:Error

Emitted when an error occurs. The 'close' event will be called directly following this event.

Emitted after resolving the host name but before connecting. Not applicable to Unix sockets.

Attributes
err:Error | null
The error object. See dns.lookup().
address:string
The IP address.
family:number | null
The address type. See dns.lookup().
host:string
The host name.
E

ready

History

Emitted when a socket is ready to be used.

Triggered immediately after 'connect'.

E

timeout

History

Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.

See also: socket.setTimeout().

socket.address(): Object
Returns:Object

Returns the bound address, the address family name and port of the socket as reported by the operating system: { port: 12346, family: 'IPv4', address: '127.0.0.1' }

P

socket.autoSelectFamilyAttemptedAddresses

History
Type:string[]

This property is only present if the family autoselection algorithm is enabled in socket.connect(options) and it is an array of the addresses that have been attempted.

Each address is a string in the form of $IP:$PORT. If the connection was successful, then the last address is the one that the socket is currently connected to.

P

socket.bufferSize

History
Stability: 0Deprecated: Use writable.writableLength instead.
Type:integer

This property shows the number of characters buffered for writing. The buffer may contain strings whose length after encoding is not yet known. So this number is only an approximation of the number of bytes in the buffer.

net.Socket has the property that socket.write() always works. This is to help users get up and running quickly. The computer cannot always keep up with the amount of data that is written to a socket. The network connection simply might be too slow. Node.js will internally queue up the data written to a socket and send it out over the wire when it is possible.

The consequence of this internal buffering is that memory may grow. Users who experience large or growing bufferSize should attempt to "throttle" the data flows in their program with socket.pause() and socket.resume().

P

socket.bytesRead

History
Type:integer

The amount of received bytes.

P

socket.bytesWritten

History
Type:integer

The amount of bytes sent.

socket.connect(): void

Initiate a connection on a given socket.

Possible signatures:

This function is asynchronous. When the connection is established, the 'connect' event will be emitted. If there is a problem connecting, instead of a 'connect' event, an 'error' event will be emitted with the error passed to the 'error' listener. The last parameter connectListener, if supplied, will be added as a listener for the 'connect' event once.

This function should only be used for reconnecting a socket after 'close' has been emitted or otherwise it may lead to undefined behavior.

socket.connect(options, connectListener?): net.Socket
Attributes
options:Object
connectListener:Function
Common parameter of socket.connect() methods. Will be added as a listener for the 'connect' event once.
Returns:net.Socket
The socket itself.

Initiate a connection on a given socket. Normally this method is not needed, the socket should be created and opened with net.createConnection(). Use this only when implementing a custom Socket.

For TCP connections, available options are:

Attributes
autoSelectFamily?:boolean
If set to true, it enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. The all option passed to lookup is set to true and the sockets attempts to connect to all obtained IPv6 and IPv4 addresses, in sequence, until a connection is established. The first returned AAAA address is tried first, then the first returned A address, then the second returned AAAA address and so on. Each connection attempt (but the last one) is given the amount of time specified by the autoSelectFamilyAttemptTimeout option before timing out and trying the next address. Ignored if the family option is not 0 or if localAddress is set. Connection errors are not emitted if at least one connection succeeds. If all connections attempts fails, a single AggregateError with all failed attempts is emitted. Default: net.getDefaultAutoSelectFamily().
autoSelectFamilyAttemptTimeout?:number
The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the autoSelectFamily option. If set to a positive integer less than 10, then the value 10 will be used instead. Default: net.getDefaultAutoSelectFamilyAttemptTimeout().
family?:number
Version of IP stack. Must be 4, 6, or 0. The value 0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.
hints:number
host?:string
Host the socket should connect to. Default: 'localhost'.
localAddress:string
Local address the socket should connect from.
localPort:number
Local port the socket should connect from.
lookup?:Function
Custom lookup function. Default: dns.lookup().
port:number
Required. Port the socket should connect to.

For IPC connections, available options are:

Attributes
path:string
Required. Path the client should connect to. See Identifying paths for IPC connections. If provided, the TCP-specific options above are ignored.
socket.connect(path, connectListener?): net.Socket
Attributes
path:string
Path the client should connect to. See Identifying paths for IPC connections.
connectListener:Function
Common parameter of socket.connect() methods. Will be added as a listener for the 'connect' event once.
Returns:net.Socket
The socket itself.

Initiate an IPC connection on the given socket.

Alias to socket.connect(options[, connectListener]) called with { path: path } as options.

M

socket.connect

History
socket.connect(port, host?, connectListener?): net.Socket
Attributes
port:number
Port the client should connect to.
host:string
Host the client should connect to.
connectListener:Function
Common parameter of socket.connect() methods. Will be added as a listener for the 'connect' event once.
Returns:net.Socket
The socket itself.

Initiate a TCP connection on the given socket.

Alias to socket.connect(options[, connectListener]) called with {port: port, host: host} as options.

P

socket.connecting

History
Type:boolean

If true, socket.connect(options[, connectListener]) was called and has not yet finished. It will stay true until the socket becomes connected, then it is set to false and the 'connect' event is emitted. Note that the socket.connect(options[, connectListener]) callback is a listener for the 'connect' event.

M

socket.destroy

History
socket.destroy(error?): net.Socket
Attributes
error:Object
Returns:net.Socket

Ensures that no more I/O activity happens on the current connection. Destroys the stream and closes the connection.

See writable.destroy() for further details.

Type:boolean
Indicates if the connection is destroyed or not. No further data can be transferred using a destroyed connection.

See writable.destroyed for further details.

M

socket.destroySoon

History
socket.destroySoon(): void

Destroys the socket after all data is written. If the 'finish' event was already emitted the socket is destroyed immediately. If the socket is still writable it implicitly calls socket.end().

M

socket.end

History
socket.end(data?, encoding?, callback?): net.Socket
Attributes
encoding?:string
Only used when data is string. Default: 'utf8'.
callback:Function
Optional callback for when the socket is finished.
Returns:net.Socket
The socket itself.

Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.

See writable.end() for further details.

P

socket.localAddress

History
Type:string

The string representation of the local IP address the remote client is connecting on. For example, in a server listening on '0.0.0.0', if a client connects on '192.168.1.1', the value of socket.localAddress would be '192.168.1.1'.

P

socket.localPort

History
Type:integer

The numeric representation of the local port. For example, 80 or 21.

P

socket.localFamily

History
Type:string

The string representation of the local IP family. 'IPv4' or 'IPv6'.

socket.pause(): net.Socket
Returns:net.Socket
The socket itself.

Pauses the reading of data. That is, 'data' events will not be emitted. Useful to throttle back an upload.

P

socket.pending

History
Type:boolean

This is true if the socket is not connected yet, either because .connect() has not yet been called or because it is still in the process of connecting (see socket.connecting).

M

socket.ref

History
socket.ref(): net.Socket
Returns:net.Socket
The socket itself.

Opposite of unref(), calling ref() on a previously unrefed socket will not let the program exit if it's the only socket left (the default behavior). If the socket is refed calling ref again will have no effect.

P

socket.remoteAddress

History
Type:string

The string representation of the remote IP address. For example, '74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if the socket is destroyed (for example, if the client disconnected).

P

socket.remoteFamily

History
Type:string

The string representation of the remote IP family. 'IPv4' or 'IPv6'. Value may be undefined if the socket is destroyed (for example, if the client disconnected).

P

socket.remotePort

History
Type:integer

The numeric representation of the remote port. For example, 80 or 21. Value may be undefined if the socket is destroyed (for example, if the client disconnected).

P

socket.server

History

Reference to the server that accepted the socket. This is null for sockets that were not accepted by a server.

M

socket.resetAndDestroy

History
socket.resetAndDestroy(): net.Socket
Returns:net.Socket

Close the TCP connection by sending an RST packet and destroy the stream. If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. Otherwise, it will call socket.destroy with an ERR_SOCKET_CLOSED Error. If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an ERR_INVALID_HANDLE_TYPE Error.

socket.resume(): net.Socket
Returns:net.Socket
The socket itself.

Resumes reading after a call to socket.pause().

M

socket.setEncoding

History
socket.setEncoding(encoding?): net.Socket
Attributes
encoding:string
Returns:net.Socket
The socket itself.

Set the encoding for the socket as a Readable Stream. See readable.setEncoding() for more information.

socket.setKeepAlive(): void

Enable/disable keep-alive functionality, and optionally configure the keepalive probe timing. Returns the socket itself.

Possible signatures:

Enabling keep-alive sets the initial delay before the first keepalive probe is sent on an idle socket.

Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Setting 0 for initialDelay will leave the value unchanged from the default (or previous) setting.

Set interval (in milliseconds) to set the delay between successive keepalive probes once they begin (TCP_KEEPINTVL). Set count to the number of unacknowledged probes sent before the connection is dropped (TCP_KEEPCNT). Both are only applied when keep-alive is enabled. Omitting interval or count uses the defaults of 1000 ms and 10. As with initialDelay, a non-positive interval or count leaves the corresponding system default unchanged.

initialDelay and interval are specified in milliseconds but the underlying socket options are configured in whole seconds; the values are divided by 1000 and rounded down before being applied.

Enabling the keep-alive functionality will set the following socket options:

  • SO_KEEPALIVE=1
  • TCP_KEEPIDLE=initialDelay / 1000
  • TCP_KEEPCNT=count
  • TCP_KEEPINTVL=interval / 1000

On Windows versions older than build 1709, keep-alive is configured through SIO_KEEPALIVE_VALS, which has no probe-count field, so count is ignored on those platforms.

M

socket.setKeepAlive

History
socket.setKeepAlive(options?): net.Socket
Attributes
options:Object
enable?:boolean
Default: false
initialDelay?:number
Default: 0
interval?:number
Default: 1000
count?:number
Default: 10
Returns:net.Socket
The socket itself.

Configure keep-alive using an options object. See socket.setKeepAlive() for a description of each property.

socket.setKeepAlive(enable?, initialDelay?, interval?, count?): net.Socket
Attributes
enable?:boolean
Default: false
initialDelay?:number
Default: 0
interval?:number
Default: 1000
count?:number
Default: 10
Returns:net.Socket
The socket itself.

Configure keep-alive using positional arguments. See socket.setKeepAlive() for a description of each argument.

M

socket.setNoDelay

History
socket.setNoDelay(noDelay?): net.Socket
Attributes
noDelay?:boolean
Default: true
Returns:net.Socket
The socket itself.

Enable/disable the use of Nagle's algorithm.

When a TCP connection is created, it will have Nagle's algorithm enabled.

Nagle's algorithm delays data before it is sent via the network. It attempts to optimize throughput at the expense of latency.

Passing true for noDelay or not passing an argument will disable Nagle's algorithm for the socket. Passing false for noDelay will enable Nagle's algorithm.

socket.setTimeout(timeout, callback?): net.Socket
Attributes
timeout:number
callback:Function
Returns:net.Socket
The socket itself.

Sets the socket to timeout after timeout milliseconds of inactivity on the socket. By default net.Socket do not have a timeout.

When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed. The user must manually call socket.end() or socket.destroy() to end the connection.

socket.setTimeout(3000);
socket.on('timeout', () => {
  console.log('socket timeout');
  socket.end();
});

If timeout is 0, then the existing idle timeout is disabled.

The optional callback parameter will be added as a one-time listener for the 'timeout' event.

M

socket.getTypeOfService

History
socket.getTypeOfService(): integer
Returns:integer
The current TOS value.

Returns the current Type of Service (TOS) field for IPv4 packets or Traffic Class for IPv6 packets for this socket.

setTypeOfService() may be called before the socket is connected; the value will be cached and applied when the socket establishes a connection. getTypeOfService() will return the currently set value even before connection.

On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored, and behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers should verify platform-specific semantics.

M

socket.setTypeOfService

History
socket.setTypeOfService(tos): net.Socket
Attributes
The TOS value to set (0-255).
Returns:net.Socket
The socket itself.

Sets the Type of Service (TOS) field for IPv4 packets or Traffic Class for IPv6 Packets sent from this socket. This can be used to prioritize network traffic.

setTypeOfService() may be called before the socket is connected; the value will be cached and applied when the socket establishes a connection. getTypeOfService() will return the currently set value even before connection.

On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored, and behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers should verify platform-specific semantics.

P

socket.timeout

History

The socket timeout in milliseconds as set by socket.setTimeout(). It is undefined if a timeout has not been set.

M

socket.unref

History
socket.unref(): net.Socket
Returns:net.Socket
The socket itself.

Calling unref() on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already unrefed calling unref() again will have no effect.

M

socket.write

History
socket.write(data, encoding?, callback?): boolean
Attributes
encoding?:string
Only used when data is string. Default: utf8.
callback:Function
Returns:boolean

Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding.

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.

The optional callback parameter will be executed when the data is finally written out, which may not be immediately.

See Writable stream write() method for more information.

P

socket.readyState

History
Type:string

This property represents the state of the connection as a string.

  • If the socket is connecting, socket.readyState is opening.
  • If the socket is readable and writable, it is open.
  • If the socket is readable and not writable, it is readOnly.
  • If the socket is not readable and writable, it is writeOnly.
  • Otherwise, it is closed.