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
Objectbooleanfalse, 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.net.BlockListblockList can be used for disabling outbound
access to specific IP addresses, IP ranges, or IP subnets.numbernet.BoundSocketBoundSocket. 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).booleantrue, it enables keep-alive functionality on
the socket immediately after the connection is established, similarly on what
is done in socket.setKeepAlive(). Default: false.number0.booleantrue, it disables the use of Nagle's algorithm
immediately after the socket is established. Default: false.Objectbuffer
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.Buffer | Uint8Array | FunctionFunctionbuffer and a reference to buffer. Return false from this function to
implicitly pause() the socket. This function will be executed in the
global context.booleanfd is passed,
otherwise ignored. Default: false.AbortSignalnumberbooleanfd is passed,
otherwise ignored. Default: false.net.SocketCreates 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.
booleantrue 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.
Emitted when a socket connection is successfully established.
See net.createConnection().
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).
Emitted when a connection attempt failed. This may be emitted multiple times
if the family autoselection algorithm is enabled in socket.connect(options).
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).
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.
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
See also: the return values of socket.write().
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).
ErrorEmitted 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.
dns.lookup().stringdns.lookup().stringEmitted when a socket is ready to be used.
Triggered immediately after 'connect'.
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
ObjectReturns 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' }
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.
writable.writableLength instead.integerThis 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().
integerThe amount of received bytes.
integerThe amount of bytes sent.
socket.connect(): void
Initiate a connection on a given socket.
Possible signatures:
socket.connect(options[, connectListener])socket.connect(path[, connectListener])for IPC connections.socket.connect(port[, host][, connectListener])for TCP connections.- Returns:
net.SocketThe socket itself.
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
History
--enable-network-family-autoselection CLI flag has been renamed to --network-family-autoselection. The old name is now an alias but it is discouraged.setDefaultAutoSelectFamily or via the command line option --enable-network-family-autoselection.autoSelectFamily option.noDelay, keepAlive, and keepAliveInitialDelay options are supported now.hints option defaults to 0 in all cases now. Previously, in the absence of the family option it would default to dns.ADDRCONFIG | dns.V4MAPPED.hints option is supported now.socket.connect(options, connectListener?): net.Socket
ObjectFunctionsocket.connect()
methods. Will be added as a listener for the 'connect' event once.net.SocketInitiate 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:
booleantrue, 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().numberautoSelectFamily option. If set to a positive integer less than
10, then the value 10 will be used instead. Default:
net.getDefaultAutoSelectFamilyAttemptTimeout().number4, 6, or 0. The value
0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.numberdns.lookup() hints.string'localhost'.stringnumberFunctiondns.lookup().numberFor IPC connections, available options are:
stringsocket.connect(path, connectListener?): net.Socket
stringFunctionsocket.connect()
methods. Will be added as a listener for the 'connect' event once.net.SocketInitiate an IPC connection on the given socket.
Alias to
socket.connect(options[, connectListener])
called with { path: path } as options.
socket.connect(port, host?, connectListener?): net.Socket
numberstringFunctionsocket.connect()
methods. Will be added as a listener for the 'connect' event once.net.SocketInitiate a TCP connection on the given socket.
Alias to
socket.connect(options[, connectListener])
called with {port: port, host: host} as options.
booleanIf 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.
socket.destroy(error?): net.Socket
Objectnet.SocketEnsures that no more I/O activity happens on the current connection. Destroys the stream and closes the connection.
See writable.destroy() for further details.
booleanSee writable.destroyed for further details.
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().
socket.end(data?, encoding?, callback?): net.Socket
string | Buffer | Uint8Arraystringstring. Default: 'utf8'.Functionnet.SocketHalf-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.
stringThe 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'.
integerThe numeric representation of the local port. For example, 80 or 21.
stringThe string representation of the local IP family. 'IPv4' or 'IPv6'.
socket.pause(): net.Socket
net.SocketPauses the reading of data. That is, 'data' events will not be emitted.
Useful to throttle back an upload.
booleanThis 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).
socket.ref(): net.Socket
net.SocketOpposite 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.
stringThe 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).
stringThe 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).
integerThe 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).
net.Server | nullReference to the server that accepted the socket. This is null for sockets
that were not accepted by a server.
socket.resetAndDestroy(): net.Socket
net.SocketClose 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
net.SocketResumes reading after a call to socket.pause().
socket.setEncoding(encoding?): net.Socket
stringnet.SocketSet 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=1TCP_KEEPIDLE=initialDelay / 1000TCP_KEEPCNT=countTCP_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.
socket.setKeepAlive(options?): net.Socket
Configure keep-alive using an options object. See socket.setKeepAlive()
for a description of each property.
socket.setKeepAlive({ enable: true, initialDelay: 1000, interval: 1000, count: 10 });
socket.setKeepAlive(enable?, initialDelay?, interval?, count?): net.Socket
booleanfalsenumber0number1000number10net.SocketConfigure keep-alive using positional arguments. See
socket.setKeepAlive() for a description of each argument.
socket.setNoDelay(noDelay?): net.Socket
booleantruenet.SocketEnable/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
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.
socket.getTypeOfService(): integer
integerReturns 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.
socket.setTypeOfService(tos): net.Socket
integernet.SocketSets 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.
The socket timeout in milliseconds as set by socket.setTimeout().
It is undefined if a timeout has not been set.
socket.unref(): net.Socket
net.SocketCalling 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.
socket.write(data, encoding?, callback?): 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.
stringThis property represents the state of the connection as a string.
- If the socket is connecting,
socket.readyStateisopening. - 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.