Module

std/node/net.ts

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

This class is used to create a TCP or IPC server.

Constructors

new
Server(connectionListener?: ConnectionListener)

net.Server is an EventEmitter with the following events:

  • "close" - Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended.
  • "connection" - Emitted when a new connection is made. socket is an instance of net.Socket.
  • "error" - Emitted when an error occurs. Unlike net.Socket, the "close" event will not be emitted directly following this event unless server.close() is manually called. See the example in discussion of server.listen().
  • "listening" - Emitted when the server has been bound after calling server.listen().
new
Server(options?: ServerOptions, connectionListener?: ConnectionListener)
new
Server(options?: ServerOptions | ConnectionListener, connectionListener?: ConnectionListener)

Properties

optional
_connectionKey: string
_connections: number
_handle: any
_listen2
optional
_pipeName: string
_unref: boolean
_usingWorkers: boolean
_workers: any[]
allowHalfOpen: boolean
readonly
listening: boolean

Indicates whether or not the server is listening for connections.

pauseOnConnect: boolean
[asyncIdSymbol]

Methods

_emitCloseIfDrained(): void
_setupWorker(socketList: EventEmitter): void
address(): AddressInfo | string | 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.

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

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

const server = net.createServer((socket: Socket) => {
  socket.end("goodbye\n");
}).on("error", (err: Error) => {
  // 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().

close(cb?: (err?: Error) => void): 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.

getConnections(cb: (err: Error | null, count: number) => void): this

Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.

Callback should take two arguments err and count.

listen(
port?: number,
hostname?: string,
backlog?: number,
listeningListener?: () => void,
): this

Start a server listening for connections. A net.Server can be a TCP or an IPC server depending on what it listens to.

Possible signatures:

  • server.listen(handle[, backlog][, callback])
  • server.listen(options[, callback])
  • server.listen(path[, backlog][, callback]) for IPC servers
  • server.listen([port[, host[, backlog]]][, callback]) for TCP servers

This function is asynchronous. When the server starts listening, the 'listening' event will be emitted. The last parameter callbackwill be added as a listener for the 'listening' event.

All listen() methods can take a backlog parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on Linux. The default value of this parameter is 511 (not 512).

All Socket are set to SO_REUSEADDR (see socket(7) for details).

The server.listen() method can be called again if and only if there was an error during the first server.listen() call or server.close() has been called. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.

One of the most common errors raised when listening is EADDRINUSE. This happens when another server is already listening on the requestedport/path/handle. One way to handle this would be to retry after a certain amount of time:

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

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

const PORT = 3000;
const HOST = "127.0.0.1";
const server = new net.Server();

server.on("error", (e: Error & { code: string; }) => {
  if (e.code === "EADDRINUSE") {
    console.log("Address in use, retrying...");
    setTimeout(() => {
      server.close();
      server.listen(PORT, HOST);
    }, 1000);
  }
});
listen(
port?: number,
hostname?: string,
listeningListener?: () => void,
): this
listen(
port?: number,
backlog?: number,
listeningListener?: () => void,
): this
listen(port?: number, listeningListener?: () => void): this
listen(
path: string,
backlog?: number,
listeningListener?: () => void,
): this
listen(path: string, listeningListener?: () => void): this
listen(options: ListenOptions, listeningListener?: () => void): this
listen(
handle: any,
backlog?: number,
listeningListener?: () => void,
): this
listen(handle: any, listeningListener?: () => void): this
listen(...args: unknown[]): this
ref(): this

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

unref(): this

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

[EventEmitter.captureRejectionSymbol](
err: Error,
event: string,
sock: Socket,
): void