Skip to main content
Socket - net - Node documentation
class Socket
extends stream.Duplex

Usage in Deno

import { Socket } from "node:net";
<div class="alert alert-warning"><div><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M12 9v4" /> <path d="M10.363 3.591l-8.106 13.534a1.914 1.914 0 0 0 1.636 2.871h16.214a1.914 1.914 0 0 0 1.636 -2.87l-8.106 -13.536a1.914 1.914 0 0 0 -3.274 0z" /> <path d="M12 16h.01" /> </svg> Deno compatibility</div><div><p> The <code>fd</code> option is not supported.</p> </div></div>

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 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 Server, so the user can use it to interact with the client.

Constructors

new
Socket(options?: SocketConstructorOpts)

Properties

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.

deprecated
readonly
bufferSize: number

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().

readonly
bytesRead: number

The amount of received bytes.

readonly
bytesWritten: number

The amount of bytes sent.

readonly
connecting: 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.

readonly
destroyed: boolean

See writable.destroyed for further details.

readonly
abstract
localAddress: 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'.

readonly
abstract
localFamily: string

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

readonly
abstract
localPort: number

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

readonly
pending: 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).

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

  • If the stream is connecting socket.readyState is opening.
  • If the stream is readable and writable, it is open.
  • If the stream is readable and not writable, it is readOnly.
  • If the stream is not readable and writable, it is writeOnly.
readonly
abstract
remoteAddress: string | undefined

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).

readonly
abstract
remoteFamily: string | undefined

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).

readonly
abstract
remotePort: number | undefined

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).

readonly
abstract
timeout: number | undefined

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

Methods

addListener(
event: string,
listener: (...args: any[]) => void,
): this

events.EventEmitter

  1. close
  2. connect
  3. connectionAttempt
  4. connectionAttemptFailed
  5. connectionAttemptTimeout
  6. data
  7. drain
  8. end
  9. error
  10. lookup
  11. ready
  12. timeout
addListener(
event: "close",
listener: (hadError: boolean) => void,
): this
addListener(
event: "connect",
listener: () => void,
): this
addListener(
event: "connectionAttempt",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
addListener(
event: "connectionAttemptFailed",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
addListener(
event: "connectionAttemptTimeout",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
addListener(
event: "data",
listener: (data: Buffer) => void,
): this
addListener(
event: "drain",
listener: () => void,
): this
addListener(
event: "end",
listener: () => void,
): this
addListener(
event: "error",
listener: (err: Error) => void,
): this
addListener(
event: "lookup",
listener: (
err: Error,
address: string,
family: string | number,
host: string,
) => void
,
): this
addListener(
event: "ready",
listener: () => void,
): this
addListener(
event: "timeout",
listener: () => void,
): this

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' }

connect(
connectionListener?: () => void,
): this

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.Socket The 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.

connect(
port: number,
host: string,
connectionListener?: () => void,
): this
connect(
port: number,
connectionListener?: () => void,
): this
connect(
path: string,
connectionListener?: () => void,
): this
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().

emit(
event: string | symbol,
...args: any[],
): boolean
emit(
event: "close",
hadError: boolean,
): boolean
emit(event: "connect"): boolean
emit(
event: "connectionAttempt",
ip: string,
port: number,
family: number,
): boolean
emit(
event: "connectionAttemptFailed",
ip: string,
port: number,
family: number,
): boolean
emit(
event: "connectionAttemptTimeout",
ip: string,
port: number,
family: number,
): boolean
emit(
event: "data",
data: Buffer,
): boolean
emit(event: "drain"): boolean
emit(event: "end"): boolean
emit(
event: "error",
err: Error,
): boolean
emit(
event: "lookup",
err: Error,
address: string,
family: string | number,
host: string,
): boolean
emit(event: "ready"): boolean
emit(event: "timeout"): boolean
end(callback?: () => void): this

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.

end(
buffer: Uint8Array | string,
callback?: () => void,
): this
end(
str: Uint8Array | string,
encoding?: BufferEncoding,
callback?: () => void,
): this
on(
event: string,
listener: (...args: any[]) => void,
): this
on(
event: "close",
listener: (hadError: boolean) => void,
): this
on(
event: "connect",
listener: () => void,
): this
on(
event: "connectionAttempt",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
on(
event: "connectionAttemptFailed",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
on(
event: "connectionAttemptTimeout",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
on(
event: "data",
listener: (data: Buffer) => void,
): this
on(
event: "drain",
listener: () => void,
): this
on(
event: "end",
listener: () => void,
): this
on(
event: "error",
listener: (err: Error) => void,
): this
on(
event: "lookup",
listener: (
err: Error,
address: string,
family: string | number,
host: string,
) => void
,
): this
on(
event: "ready",
listener: () => void,
): this
on(
event: "timeout",
listener: () => void,
): this
once(
event: string,
listener: (...args: any[]) => void,
): this
once(
event: "close",
listener: (hadError: boolean) => void,
): this
once(
event: "connectionAttempt",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
once(
event: "connectionAttemptFailed",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
once(
event: "connectionAttemptTimeout",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
once(
event: "connect",
listener: () => void,
): this
once(
event: "data",
listener: (data: Buffer) => void,
): this
once(
event: "drain",
listener: () => void,
): this
once(
event: "end",
listener: () => void,
): this
once(
event: "error",
listener: (err: Error) => void,
): this
once(
event: "lookup",
listener: (
err: Error,
address: string,
family: string | number,
host: string,
) => void
,
): this
once(
event: "ready",
listener: () => void,
): this
once(
event: "timeout",
listener: () => void,
): this
pause(): this

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

prependListener(
event: string,
listener: (...args: any[]) => void,
): this
prependListener(
event: "close",
listener: (hadError: boolean) => void,
): this
prependListener(
event: "connect",
listener: () => void,
): this
prependListener(
event: "connectionAttempt",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
prependListener(
event: "connectionAttemptFailed",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
prependListener(
event: "connectionAttemptTimeout",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
prependListener(
event: "data",
listener: (data: Buffer) => void,
): this
prependListener(
event: "drain",
listener: () => void,
): this
prependListener(
event: "end",
listener: () => void,
): this
prependListener(
event: "error",
listener: (err: Error) => void,
): this
prependListener(
event: "lookup",
listener: (
err: Error,
address: string,
family: string | number,
host: string,
) => void
,
): this
prependListener(
event: "ready",
listener: () => void,
): this
prependListener(
event: "timeout",
listener: () => void,
): this
prependOnceListener(
event: string,
listener: (...args: any[]) => void,
): this
prependOnceListener(
event: "close",
listener: (hadError: boolean) => void,
): this
prependOnceListener(
event: "connect",
listener: () => void,
): this
prependOnceListener(
event: "connectionAttempt",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
prependOnceListener(
event: "connectionAttemptFailed",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
prependOnceListener(
event: "connectionAttemptTimeout",
listener: (
ip: string,
port: number,
family: number,
) => void
,
): this
prependOnceListener(
event: "data",
listener: (data: Buffer) => void,
): this
prependOnceListener(
event: "drain",
listener: () => void,
): this
prependOnceListener(
event: "end",
listener: () => void,
): this
prependOnceListener(
event: "error",
listener: (err: Error) => void,
): this
prependOnceListener(
event: "lookup",
listener: (
err: Error,
address: string,
family: string | number,
host: string,
) => void
,
): this
prependOnceListener(
event: "ready",
listener: () => void,
): this
prependOnceListener(
event: "timeout",
listener: () => void,
): this
ref(): this

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.

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.

resume(): this

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

setEncoding(encoding?: BufferEncoding): this

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

setKeepAlive(
enable?: boolean,
initialDelay?: number,
): this

Enable/disable keep-alive functionality, and optionally set 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 forinitialDelay will leave the value unchanged from the default (or previous) setting.

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

  • SO_KEEPALIVE=1
  • TCP_KEEPIDLE=initialDelay
  • TCP_KEEPCNT=10
  • TCP_KEEPINTVL=1
setNoDelay(noDelay?: boolean): this

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.

setTimeout(
timeout: number,
callback?: () => void,
): this

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.

unref(): this

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 callingunref() again will have no effect.

write(
buffer: Uint8Array | string,
cb?: (err?: Error) => void,
): 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.

write(
str: Uint8Array | string,
encoding?: BufferEncoding,
cb?: (err?: Error) => void,
): boolean