Server

Exposed by require("socket.io").

Related documentation pages:

new Server(httpServer[, options])

  • httpServer (http.Server) the server to bind to.
  • options (Object)

Works with and without new:

  1. const io = require("socket.io")();
    // or
    const { Server } = require("socket.io");
    const io = new Server();

Available options:

OptionDefault valueDescription
path/socket.ioname of the path to capture
serveClienttruewhether to serve the client files
adapter-the adapter to use. Defaults to an instance of the Adapter that ships with socket.io which is memory based. See socket.io-adapter
parser-the parser to use. Defaults to an instance of the Parser that ships with socket.io. See socket.io-parser.
connectTimeout45000the number of ms before closing a client that has not successfully joined a namespace.

Available options for the underlying Engine.IO server:

OptionDefault valueDescription
pingTimeout20000how many ms without a pong packet to consider the connection closed
pingInterval25000how many ms before sending a new ping packet
upgradeTimeout10000how many ms before an uncompleted transport upgrade is cancelled
maxHttpBufferSize1e6how many bytes or characters a message can be, before closing the session (to avoid DoS).
allowRequestA function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not. The second argument is a function that needs to be called with the decided information: fn(err, success), where success is a boolean value where false means that the request is rejected, and err is an error code.
transports[“polling”, “websocket”]transports to allow connections to
allowUpgradestruewhether to allow transport upgrades
perMessageDeflatefalseparameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to true to enable.
httpCompressiontrueparameters of the http compression for the polling transports (see zlib api docs). Set to false to disable.
wsEnginewswhat WebSocket server implementation to use. Specified module must conform to the ws interface (see ws module api docs). Default value is ws. An alternative c++ addon is also available by installing the eiows module.
corsthe list of options that will be forwarded to the cors module
cookiethe list of options that will be forwarded to the cookie module
allowEIO3falsewhether to enable compatibility with Socket.IO v2 clients

More information here.

new Server(port[, options])

  • port (Number) a port to listen to (a new http.Server will be created)
  • options (Object)

See above for the list of available options.

  1. const io = require("socket.io")(3000, {
    path: "/test",
    serveClient: false,
    // below are engine.IO options
    pingInterval: 10000,
    pingTimeout: 5000,
    cookie: false
    });

new Server(options)

  • options (Object)

See above for the list of available options.

  1. const io = require("socket.io")({
    path: "/test",
    serveClient: false,
    });

    // either
    const server = require("http").createServer();

    io.attach(server, {
    pingInterval: 10000,
    pingTimeout: 5000,
    cookie: false
    });

    server.listen(3000);

    // or
    io.attach(3000, {
    pingInterval: 10000,
    pingTimeout: 5000,
    cookie: false
    });

server.sockets

  • (Namespace)

An alias for the default (/) namespace.

  1. io.sockets.emit("hi", "everyone");
    // is equivalent to
    io.of("/").emit("hi", "everyone");

server.serveClient([value])

  • value (Boolean)
  • Returns Server|Boolean

If value is true the attached server (see Server#attach) will serve the client files. Defaults to true. This method has no effect after attach is called. If no arguments are supplied this method returns the current value.

  1. // pass a server and the `serveClient` option
    const io = require("socket.io")(http, { serveClient: false });

    // or pass no server and then you can call the method
    const io = require("socket.io")();
    io.serveClient(false);
    io.attach(http);

server.path([value])

  • value (String)
  • Returns Server|String

Sets the path value under which engine.io and the static files will be served. Defaults to /socket.io. If no arguments are supplied this method returns the current value.

  1. const io = require("socket.io")();
    io.path("/myownpath");

    // client-side
    const socket = io({
    path: "/myownpath"
    });

server.adapter([value])

  • value (Adapter)
  • Returns Server|Adapter

Sets the adapter value. Defaults to an instance of the Adapter that ships with socket.io which is memory based. See socket.io-adapter. If no arguments are supplied this method returns the current value.

  1. const io = require("socket.io")(3000);
    const redis = require("socket.io-redis");
    io.adapter(redis({ host: "localhost", port: 6379 }));

server.attach(httpServer[, options])

  • httpServer (http.Server) the server to attach to
  • options (Object)

Attaches the Server to an engine.io instance on httpServer with the supplied options (optionally).

server.attach(port[, options])

  • port (Number) the port to listen on
  • options (Object)

Attaches the Server to an engine.io instance on a new http.Server with the supplied options (optionally).

server.listen(httpServer[, options])

Synonym of server.attach(httpServer[, options]).

server.listen(port[, options])

Synonym of server.attach(port[, options]).

server.bind(engine)

  • engine (engine.Server)
  • Returns Server

Advanced use only. Binds the server to a specific engine.io Server (or compatible API) instance.

server.onconnection(socket)

  • socket (engine.Socket)
  • Returns Server

Advanced use only. Creates a new socket.io client from the incoming engine.io (or compatible API) Socket.

server.of(nsp)

  • nsp (String|RegExp|Function)
  • Returns Namespace

Initializes and retrieves the given Namespace by its pathname identifier nsp. If the namespace was already initialized it returns it immediately.

  1. const adminNamespace = io.of("/admin");

A regex or a function can also be provided, in order to create namespace in a dynamic way:

  1. const dynamicNsp = io.of(/^\/dynamic-\d+$/).on("connection", (socket) => {
    const newNamespace = socket.nsp; // newNamespace.name === "/dynamic-101"

    // broadcast to all clients in the given sub-namespace
    newNamespace.emit("hello");
    });

    // client-side
    const socket = io("/dynamic-101");

    // broadcast to all clients in each sub-namespace
    dynamicNsp.emit("hello");

    // use a middleware for each sub-namespace
    dynamicNsp.use((socket, next) => { /* ... */ });

With a function:

  1. io.of((name, query, next) => {
    // the checkToken method must return a boolean, indicating whether the client is able to connect or not.
    next(null, checkToken(query.token));
    }).on("connection", (socket) => { /* ... */ });

server.close([callback])

  • callback (Function)

Closes the Socket.IO server. The callback argument is optional and will be called when all connections are closed.

Note: this also closes the underlying HTTP server.

  1. const Server = require("socket.io");
    const PORT = 3030;
    const server = require("http").Server();

    const io = Server(PORT);

    io.close(); // Close current server

    server.listen(PORT); // PORT is free to use

    io = Server(server);

server.engine

A reference to the underlying Engine.IO server. See here.

server.socketsJoin(rooms)

Added in v4.0.0

Alias for io.of("/").socketsJoin(rooms).

  1. // make all Socket instances join the "room1" room
    io.socketsJoin("room1");

    // make all Socket instances in the "room1" room join the "room2" and "room3" rooms
    io.in("room1").socketsJoin(["room2", "room3"]);

    // this also works with a single socket ID
    io.in(theSocketId).socketsJoin("room1");

See here.

server.socketsLeave(rooms)

Added in v4.0.0

Alias for io.of("/").socketsLeave(rooms).

  1. // make all Socket instances leave the "room1" room
    io.socketsLeave("room1");

    // make all Socket instances in the "room1" room leave the "room2" and "room3" rooms
    io.in("room1").socketsLeave(["room2", "room3"]);

    // this also works with a single socket ID
    io.in(theSocketId).socketsLeave("room1");

See here.

server.disconnectSockets([close])

Added in v4.0.0

Alias for io.of("/").disconnectSockets(close).

  1. // make all Socket instances disconnect
    io.disconnectSockets();

    // make all Socket instances in the "room1" room disconnect (and close the low-level connection)
    io.in("room1").disconnectSockets(true);

See here.

server.fetchSockets()

Added in v4.0.0

  1. // return all Socket instances
    const sockets = await io.fetchSockets();

    // return all Socket instances in the "room1" room of the main namespace
    const sockets = await io.in("room1").fetchSockets();

See here.

server.serverSideEmit(eventName[, …args][, ack])

Added in v4.1.0

Synonym of: io.of("/").serverSideEmit(/* ... */);

See here.

Event: connection

  • socket (Socket) socket connection with client

Fired upon a connection from client.

  1. io.on("connection", (socket) => {
    // ...
    });

Event: connect

Synonym of Event: “connection”.

Event: new_namespace

  • namespace (Namespace) the new namespace

Fired when a new namespace is created:

  1. io.on("new_namespace", (namespace) => {
    // ...
    });

This can be useful for example:

  • to attach a shared middleware to each namespace
  1. io.on("new_namespace", (namespace) => {
    namespace.use(myMiddleware);
    });
  1. io.of(/\/nsp-\w+/);

    io.on("new_namespace", (namespace) => {
    console.log(namespace.name);
    });