Skip to content

@fkn/lib/net

  • EventEmitter
new Server(options?, connectionListener?): Server;

ServerOpts & EventEmitterOptions & object

(socket) => void

Server

EventEmitter.constructor
connections: number;
TCPServer.connections
listening: boolean;

Indicates whether or not the server is listening for connections.

v5.7.0

TCPServer.listening
maxConnections: number;

Set this property to reject connections when the server’s connection count gets high.

It is not recommended to use this option once a socket has been sent to a child with child_process.fork().

v0.2.0

TCPServer.maxConnections
asyncDispose: Promise<void>;

Promise<void>

TCPServer.[asyncDispose]
address(): string | AddressInfo | null;

Returns the bound address, the address family name, and port of the server as reported by the operating system if listening on an IP socket (useful to find which port was assigned when getting an OS-assigned address):{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

For a server listening on a pipe or Unix domain socket, the name is returned as a string.

const server = net.createServer((socket) => {
socket.end('goodbye\n');
}).on('error', (err) => {
// Handle errors here.
throw err;
});
// Grab an arbitrary unused port.
server.listen(() => {
console.log('opened server on', server.address());
});

server.address() returns null before the 'listening' event has been emitted or after calling server.close().

string | AddressInfo | null

v0.1.90

TCPServer.address
close(callback?): this;

Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a 'close' event. The optional callback will be called once the 'close' event occurs. Unlike that event, it will be called with an Error as its only argument if the server was not open when it was closed.

(err?) => void

Called when the server is closed.

this

v0.1.90

TCPServer.close
getConnections(cb): this;

Not implemented by the browser transport. This method throws.

(error, count) => void

this

TCPServer.getConnections
listen(
port?,
hostname?,
backlog?,
listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

number

string

number

() => void

this

TCPServer.listen
listen(
port?,
hostname?,
listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

number

string

() => void

this

TCPServer.listen
listen(
port?,
backlog?,
listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

number

number

() => void

this

TCPServer.listen
listen(port?, listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

number

() => void

this

TCPServer.listen
listen(
path,
backlog?,
listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

string

number

() => void

this

TCPServer.listen
listen(path, listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

string

() => void

this

TCPServer.listen
listen(options, listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

ListenOptions

() => void

this

TCPServer.listen
listen(
handle,
backlog?,
listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

any

number

() => void

this

TCPServer.listen
listen(handle, listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

any

() => void

this

TCPServer.listen
listen(
port?,
hostname?,
backlog?,
listeningListener?): this;

Starts a TCP listener through WebVPN. Port and host forms are supported. IPC paths and existing Node handles are not supported and reject at runtime.

unknown

unknown

unknown

unknown

this

TCPServer.listen
ref(): this;

No-op in a browser, which has no Node process-liveness handle.

this

TCPServer.ref
unref(): this;

No-op in a browser, which has no Node process-liveness handle.

this

TCPServer.unref

  • Duplex
new Socket(options?): Socket;

SocketConstructorOpts & DuplexOptions<Duplex> & object

Socket

Stream.Duplex.constructor
autoSelectFamilyAttemptedAddresses: 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.

v19.4.0

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

v0.3.8

Since v14.6.0 - Use writableLength instead.

NetSocket.bufferSize
bytesRead: number;

The amount of received bytes.

v0.5.3

NetSocket.bytesRead
bytesWritten: number;

The amount of bytes sent.

v0.5.3

NetSocket.bytesWritten
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.

v6.1.0

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

v11.2.0, v10.16.0

NetSocket.pending
readyState: "closed" | "opening" | "open" | "readOnly" | "writeOnly";

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.

v0.5.0

NetSocket.readyState
optional timeout?: number;

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

v10.7.0

NetSocket.timeout
get 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'.

v0.9.6

string

NetSocket.localAddress
get localFamily(): string;

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

v18.8.0, v16.18.0

string

NetSocket.localFamily
get localPort(): number;

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

v0.9.6

number

NetSocket.localPort
get remoteAddress(): 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).

v0.5.10

string

NetSocket.remoteAddress
get remoteFamily(): 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).

v0.11.14

string

NetSocket.remoteFamily
get remotePort(): number;

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

v0.5.10

number

NetSocket.remotePort
address():
| {
}
| AddressInfo;

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

| { } | AddressInfo

v0.1.90

NetSocket.address
connect(options, connectionListener?): this;

SOCKET IMPL

SocketConnectOpts

() => void

this

NetSocket.connect
connect(
port,
host,
connectionListener?): this;

SOCKET IMPL

number

string

() => void

this

NetSocket.connect
connect(port, connectionListener?): this;

SOCKET IMPL

number

() => void

this

NetSocket.connect
connect(path, connectionListener?): this;

SOCKET IMPL

string

() => void

this

NetSocket.connect
connect(
port,
host?,
connectionListener?): this;

SOCKET IMPL

unknown

unknown

unknown

this

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

void

v0.3.4

NetSocket.destroySoon
getTypeOfService(): number;

number

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.

this

The socket itself.

v0.9.1

NetSocket.ref
resetAndDestroy(): this;

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.

this

v18.3.0, v16.17.0

NetSocket.resetAndDestroy
setKeepAlive(enable?, initialDelay?): 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

boolean

number

this

The socket itself.

v0.1.92

NetSocket.setKeepAlive
setNoDelay(noDelay?): 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.

boolean

this

The socket itself.

v0.1.90

NetSocket.setNoDelay
setRecvBufferSize(size): this;

number

this

setSendBufferSize(size): this;

number

this

setTimeout(timeout, callback?): 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.

number

() => void

this

The socket itself.

v0.1.90

NetSocket.setTimeout
setTypeOfService(tos): this;

number

this

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.

this

The socket itself.

v0.9.1

NetSocket.unref
write(buffer, cb?): boolean;

The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument. The callback is called asynchronously and before 'error' is emitted.

The return value is true if the internal buffer is less than the highWaterMark configured when the stream was created after admitting chunk. If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. Once write() returns false, do not write more chunks until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining can keep buffering until the process runs out of memory.

Writing data while the stream is not draining is particularly problematic for a Transform, because the Transform streams are paused by default until they are piped or a 'data' or 'readable' event handler is added.

If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is possible to respect backpressure and avoid memory issues using the 'drain' event:

function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});

A Writable stream in object mode will always ignore the encoding argument.

string | Uint8Array<ArrayBufferLike>

(err?) => void

boolean

false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.

v0.9.4

NetSocket.write
Stream.Duplex.write
write(
str,
encoding?,
cb?): boolean;

string | Uint8Array<ArrayBufferLike>

BufferEncoding

(err?) => void

boolean

NetSocket.write
Stream.Duplex.write
const _default: object;
connect: (options, connectionListener?) => Socket;

SocketConnectOpts

() => void

Socket

createConnection: (options, connectionListener?) => Socket;

SocketConnectOpts

() => void

Socket

createServer: (options?, connectionListener?) => Server;

ServerOpts | ((socket) => void)

(socket) => void

Server

isIP: (input) => 0 | 4 | 6;

string

0 | 4 | 6

isIPv4: (input) => boolean;

string

boolean

isIPv6: (input) => boolean;

string

boolean

Server: typeof Server;
Socket: typeof Socket;
function connect(options, connectionListener?): Socket;

SocketConnectOpts

() => void

Socket


function createConnection(options, connectionListener?): Socket;

SocketConnectOpts

() => void

Socket


function createServer(options?, connectionListener?): Server;

ServerOpts | ((socket) => void)

(socket) => void

Server

Renames and re-exports _default


Re-exports isIP


Re-exports isIPv4


Re-exports isIPv6