Module

std/node/net.ts>Socket

Deno standard library
Go to Latest
class Socket
extends Duplex
import { Socket } from "https://deno.land/std@0.145.0/node/net.ts";

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: SocketOptions | number)

Properties

readonly
_bytesDispatched: number
readonly
_connecting: boolean
_handle: Handle | null
_host: string | null
_parent: any
optional
_peername: AddressInfo | Record<string, never>
_pendingData: Uint8Array | string | null
_pendingEncoding: string
_server: any
optional
_sockname: AddressInfo | Record<string, never>
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 | undefined

The amount of bytes sent.

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
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
localPort: number

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

readonly
pending: boolean
readonly
readyState: string
readonly
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
remoteFamily: string | undefined

The string representation of the remote IP family. "IPv4" or "IPv6".

readonly
remotePort: number | undefined

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

server
setTimeout

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.

import { createRequire } from "https://deno.land/std@0.145.0/node/module.ts";

const require = createRequire(import.meta.url);
const net = require("net");

const socket = new net.Socket();
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.

[asyncIdSymbol]
[kBuffer]: Uint8Array | boolean | null
[kBufferCb]: OnReadOptions["callback"] | null
[kBufferGen]: (() => Uint8Array) | null
[kBytesRead]: number
[kBytesWritten]: number
[kHandle]: Handle | null
[kLastWriteQueueSize]: number
[kSetNoDelay]: boolean
[kTimeout]: any
readonly
[kUpdateTimer]

Methods

_destroy(exception: Error | null, cb: (err: Error | null) => void)
_final(cb: any): any
_getpeername(): AddressInfo | Record<string, never>
_getsockname(): AddressInfo | Record<string, never>
_read(size?: number): void
_write(
data: any,
encoding: string,
cb: (error?: Error | null) => void,
)
_writeGeneric(
writev: boolean,
data: any,
encoding: string,
cb: (error?: Error | null) => void,
)
_writev(chunks: Array<{ chunk: any; encoding: string; }>, cb: (error?: Error | null) => void)
address(): AddressInfo | Record<string, never>

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(options: SocketConnectOptions | NormalizedArgs, connectionListener?: ConnectionListener): 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?: ConnectionListener,
): this
connect(port: number, connectionListener?: ConnectionListener): this
connect(path: string, connectionListener?: ConnectionListener): this
connect(...args: unknown[]): this
destroySoon(): void
end(cb?: () => 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, cb?: () => void): this
end(
data: Uint8Array | string,
encoding?: Encodings,
cb?: () => void,
): this
end(
data?: Uint8Array | string | (() => void),
encoding?: Encodings | (() => void),
cb?: () => void,
): this
pause(): this

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

read(size?: number):
| string
| Uint8Array
| null
| undefined
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.

resume(): this

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

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.

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.