Server API

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:

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

Available options:

Option Default value Description
path /socket.io name of the path to capture
serveClient true whether 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.
connectTimeout 45000 the number of ms before closing a client that has not successfully joined a namespace.

Available options for the underlying Engine.IO server:

Option Default value Description
pingTimeout 20000 how many ms without a pong packet to consider the connection closed
pingInterval 25000 how many ms before sending a new ping packet
upgradeTimeout 10000 how many ms before an uncompleted transport upgrade is cancelled
maxHttpBufferSize 1e6 how many bytes or characters a message can be, before closing the session (to avoid DoS).
allowRequest A 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
allowUpgrades true whether to allow transport upgrades
perMessageDeflate false parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to true to enable.
httpCompression true parameters of the http compression for the polling transports (see zlib api docs). Set to false to disable.
wsEngine ws what 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.
cors the list of options that will be forwarded to the cors module
cookie the list of options that will be forwarded to the cookie module
allowEIO3 false whether 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.

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.

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.

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.

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

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.

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.

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

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

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:

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.

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 (more information here).

It can be used to fetch the number of currently connected clients:

const count = io.engine.clientsCount;

As of [email protected], the Engine.IO server emits three special events:

  • initial_headers: will be emitted just before writing the response headers of the first HTTP request of the session (the handshake), allowing you to customize them.
io.engine.on("initial_headers", (headers, req) => {
  headers["test"] = "123";
  headers["set-cookie"] = "mycookie=456";
});
  • headers: : will be emitted just before writing the response headers of each HTTP request of the session (including the WebSocket upgrade), allowing you to customize them.
io.engine.on("headers", (headers, req) => {
  headers["test"] = "789";
});
  • connection_error: will be emitted when a connection is abnormally closed
io.engine.on("connection_error", (err) => {
  console.log(err.req);	     // the request object
  console.log(err.code);     // the error code, for example 1
  console.log(err.message);  // the error message, for example "Session ID unknown"
  console.log(err.context);  // some additional error context
});

Here is the list of possible error codes:

Code Message
0 “Transport unknown”
1 “Session ID unknown”
2 “Bad handshake method”
3 “Bad request”
4 “Forbidden”
5 “Unsupported protocol version”

server.socketsJoin(rooms)

Added in v4.0.0

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

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

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

// 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

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

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:

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

This can be useful for example:

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

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

Namespace

Represents a pool of sockets connected under a given scope identified by a pathname (eg: /chat).

More information can be found here.

namespace.name

  • (String)

The namespace identifier property.

namespace.sockets

  • (Map<SocketId, Socket>)

A map of Socket instances that are connected to this namespace.

// number of sockets in this namespace (on this node)
const socketCount = io.of("/admin").sockets.size;

namespace.adapter

  • (Adapter)

The “Adapter” used for the namespace. Useful when using the Adapter based on Redis, as it exposes methods to manage sockets and rooms across your cluster.

Note: the adapter of the main namespace can be accessed with io.of("/").adapter.

Please see the explanation here.

namespace.to(room)

History
Version Changes
v4.0.0 Allow to pass an array of rooms.
v1.0.0 Initial implementation.
  • room (string) | (string[])
  • Returns BroadcastOperator for chaining

Sets a modifier for a subsequent event emission that the event will only be broadcast to clients that have joined the given room.

To emit to multiple rooms, you can call to several times.

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

adminNamespace.to("level1").emit("an event", { some: "data" });

// multiple rooms
io.to("room1").to("room2").emit(/* ... */);

// or with an array
io.to(["room1", "room2"]).emit(/* ... */);

namespace.in(room)

Added in v1.0.0

Synonym of namespace.to(room).

namespace.except(rooms)

Added in v4.0.0

  • rooms (string) | (string[])
  • Returns BroadcastOperator

Sets a modifier for a subsequent event emission that the event will only be broadcast to clients that have not joined the given rooms.

// to all clients except the ones in "room1"
io.except("room1").emit(/* ... */);

// to all clients in "room2" except the ones in "room3"
io.to("room2").except("room3").emit(/* ... */);

namespace.emit(eventName[, …args])

  • eventName (String)
  • args
  • Returns true

Emits an event to all connected clients. The following two are equivalent:

const io = require("socket.io")();
io.emit("an event sent to all connected clients"); // main namespace

const chat = io.of("/chat");
chat.emit("an event sent to all connected clients in chat namespace");

Note: acknowledgements are not supported when emitting from namespace.

namespace.allSockets()

  • Returns Promise<Set<SocketId>>

Gets a list of socket IDs connected to this namespace (across all nodes if applicable).

// all sockets in the main namespace
const ids = await io.allSockets();

// all sockets in the main namespace and in the "user:1234" room
const ids = await io.in("user:1234").allSockets();

// all sockets in the "chat" namespace
const ids = await io.of("/chat").allSockets();

// all sockets in the "chat" namespace and in the "general" room
const ids = await io.of("/chat").in("general").allSockets();

namespace.use(fn)

  • fn (Function)

Registers a middleware, which is a function that gets executed for every incoming Socket, and receives as parameters the socket and a function to optionally defer execution to the next registered middleware.

Errors passed to middleware callbacks are sent as special connect_error packets to clients.

// server-side
io.use((socket, next) => {
  const err = new Error("not authorized");
  err.data = { content: "Please retry later" }; // additional details
  next(err);
});

// client-side
socket.on("connect_error", err => {
  console.log(err instanceof Error); // true
  console.log(err.message); // not authorized
  console.log(err.data); // { content: "Please retry later" }
});

More information can be found here.

namespace.socketsJoin(rooms)

Added in v4.0.0

  • rooms (string) | (string[])
  • Returns void

Makes the matching Socket instances join the specified rooms:

// 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"]);

// make all Socket instances in the "room1" room of the "admin" namespace join the "room2" room
io.of("/admin").in("room1").socketsJoin("room2");

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

More information can be found here.

namespace.socketsLeave(rooms)

Added in v4.0.0

  • rooms (string) | (string[])
  • Returns void

Makes the matching Socket instances leave the specified rooms:

// 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"]);

// make all Socket instances in the "room1" room of the "admin" namespace leave the "room2" room
io.of("/admin").in("room1").socketsLeave("room2");

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

namespace.disconnectSockets([close])

Added in v4.0.0

  • close (Boolean) whether to close the underlying connection
  • Returns void

Makes the matching Socket instances disconnect.

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

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

// make all Socket instances in the "room1" room of the "admin" namespace disconnect
io.of("/admin").in("room1").disconnectSockets();

// this also works with a single socket ID
io.of("/admin").in(theSocketId).disconnectSockets();

namespace.fetchSockets()

Added in v4.0.0

  • Returns (Socket | RemoteSocket)[]

Returns the matching Socket instances:

// 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();

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

// this also works with a single socket ID
const sockets = await io.in(theSocketId).fetchSockets();

The sockets variable in the example above is an array of objects exposing a subset of the usual Socket class:

for (const socket of sockets) {
  console.log(socket.id);
  console.log(socket.handshake);
  console.log(socket.rooms);
  console.log(socket.data);
  socket.emit(/* ... */);
  socket.join(/* ... */);
  socket.leave(/* ... */);
  socket.disconnect(/* ... */);
}

The data attribute is an arbitrary object that can be used to share information between Socket.IO servers:

// server A
io.on("connection", (socket) => {
  socket.data.username = "alice";
});

// server B
const sockets = await io.fetchSockets();
console.log(sockets[0].data.username); // "alice"

Important note: this method (and socketsJoin, socketsLeave and disconnectSockets too) is compatible with the Redis adapter (starting with [email protected]), which means that they will work across Socket.IO servers.

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

Added in v4.1.0

  • eventName (String)
  • args
  • ack (Function)
  • Returns true

Sends a message to the other Socket.IO servers of the cluster.

Syntax:

io.serverSideEmit("hello", "world");

And on the receiving side:

io.on("hello", (arg1) => {
  console.log(arg1); // prints "world"
});

Acknowledgements are supported too:

// server A
io.serverSideEmit("ping", (err, responses) => {
  console.log(responses[0]); // prints "pong"
});

// server B
io.on("ping", (cb) => {
  cb("pong");
});

Notes:

  • the connection, connect and new_namespace strings are reserved and cannot be used in your application.

  • you can send any number of arguments, but binary structures are currently not supported (the array of arguments will be JSON.stringify-ed)

Example:

io.serverSideEmit("hello", "world", 1, "2", { 3: "4" });
  • the acknowledgement callback might be called with an error, if the other Socket.IO servers do not respond after a given delay
io.serverSideEmit("ping", (err, responses) => {
  if (err) {
    // at least one Socket.IO server has not responded
    // the 'responses' array contains all the responses already received though
  } else {
    // success! the 'responses' array contains one object per other Socket.IO server in the cluster
  }
});

Event: ‘connection’

  • socket (Socket) socket connection with client

Fired upon a connection from client.

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

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

Event: ‘connect’

Synonym of Event: “connection”.

Flag: ‘volatile’

Sets a modifier for a subsequent event emission that the event data may be lost if the clients are not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).

io.volatile.emit("an event", { some: "data" }); // the clients may or may not receive it

Flag: ‘local’

Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node (when the Redis adapter is used).

io.local.emit("an event", { some: "data" });

Socket

A Socket is the fundamental class for interacting with browser clients. A Socket belongs to a certain Namespace (by default /) and uses an underlying Client to communicate.

It should be noted the Socket doesn’t relate directly to the actual underlying TCP/IP socket and it is only the name of the class.

Within each Namespace, you can also define arbitrary channels (called room) that the Socket can join and leave. That provides a convenient way to broadcast to a group of Sockets (see Socket#to below).

The Socket class inherits from EventEmitter. The Socket class overrides the emit method, and does not modify any other EventEmitter method. All methods documented here which also appear as EventEmitter methods (apart from emit) are implemented by EventEmitter, and documentation for EventEmitter applies.

More information can be found here.

socket.id

  • (String)

A unique identifier for the session, that comes from the underlying Client.

socket.rooms

  • (Set)

A Set of strings identifying the rooms this client is in.

io.on("connection", (socket) => {

  console.log(socket.rooms); // Set { <socket.id> }

  socket.join("room1");

  console.log(socket.rooms); // Set { <socket.id>, "room1" }

});

socket.client

  • (Client)

A reference to the underlying Client object.

socket.conn

  • (engine.Socket)

A reference to the underlying Client transport connection (engine.io Socket object). This allows access to the IO transport layer, which still (mostly) abstracts the actual TCP/IP socket.

socket.request

  • (Request)

A getter proxy that returns the reference to the request that originated the underlying engine.io Client. Useful for accessing request headers such as Cookie or User-Agent.

const cookie = require("cookie");

io.on("connection", (socket) => {
  const cookies = cookie.parse(socket.request.headers.cookie || "");
});

socket.handshake

  • (Object)

The handshake details:

{
  headers: /* the headers sent as part of the handshake */,
  time: /* the date of creation (as string) */,
  address: /* the ip of the client */,
  xdomain: /* whether the connection is cross-domain */,
  secure: /* whether the connection is secure */,
  issued: /* the date of creation (as unix timestamp) */,
  url: /* the request URL string */,
  query: /* the query params of the first request */,
  auth: /* the authentication payload */
}

Usage:

io.use((socket, next) => {
  let handshake = socket.handshake;
  // ...
});

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

socket.use(fn)

History
Version Changes
v3.0.5 Restoration of the first implementation.
v3.0.0 Removal in favor of socket.onAny().
v1.7.2 The error event is sent directly to the client.
v1.6.0 First implementation.
  • fn (Function)

Registers a middleware, which is a function that gets executed for every incoming Packet and receives as parameter the packet and a function to optionally defer execution to the next registered middleware.

Errors passed to the middleware callback are then emitted as error events on the server-side:

io.on("connection", (socket) => {
  socket.use(([event, ...args], next) => {
    if (isUnauthorized(event)) {
      return next(new Error("unauthorized event"));
    }
    // do not forget to call next
    next();
  });

  socket.on("error", (err) => {
    if (err && err.message === "unauthorized event") {
      socket.disconnect();
    }
  });
});

socket.send([…args][, ack])

  • args
  • ack (Function)
  • Returns Socket

Sends a message event. See socket.emit(eventName[, …args][, ack]).

socket.emit(eventName[, …args][, ack])

(overrides EventEmitter.emit)

  • eventName (String)
  • args
  • ack (Function)
  • Returns true

Emits an event to the socket identified by the string name. Any other parameters can be included. All serializable datastructures are supported, including Buffer.

socket.emit("hello", "world");
socket.emit("with-binary", 1, "2", { 3: "4", 5: Buffer.from([6]) });

The ack argument is optional and will be called with the client’s answer.

io.on("connection", (socket) => {
  socket.emit("an event", { some: "data" });

  socket.emit("ferret", "tobi", (data) => {
    console.log(data); // data will be "woot"
  });

  // the client code
  // client.on("ferret", (name, fn) => {
  //   fn("woot");
  // });

});

socket.on(eventName, callback)

(inherited from EventEmitter)

  • eventName (String)
  • callback (Function)
  • Returns Socket

Register a new handler for the given event.

socket.on("news", (data) => {
  console.log(data);
});
// with several arguments
socket.on("news", (arg1, arg2, arg3) => {
  // ...
});
// or with acknowledgement
socket.on("news", (data, callback) => {
  callback(0);
});

socket.once(eventName, listener)

socket.removeListener(eventName, listener)

socket.removeAllListeners([eventName])

socket.eventNames()

Inherited from EventEmitter (along with other methods not mentioned here). See the Node.js documentation for the events module.

socket.onAny(callback)

  • callback (Function)

Register a new catch-all listener.

socket.onAny((event, ...args) => {
  console.log(`got ${event}`);
});

socket.prependAny(callback)

  • callback (Function)

Register a new catch-all listener. The listener is added to the beginning of the listeners array.

socket.prependAny((event, ...args) => {
  console.log(`got ${event}`);
});

socket.offAny([listener])

  • listener (Function)

Removes the previously registered listener. If no listener is provided, all catch-all listeners are removed.

const myListener = () => { /* ... */ };

socket.onAny(myListener);

// then, later
socket.offAny(myListener);

socket.offAny();

socket.listenersAny()

  • Returns Function[]

Returns the list of registered catch-all listeners.

const listeners = socket.listenersAny();

socket.join(room)

  • room (string) | (string[])
  • Returns void | Promise

Adds the socket to the given room or to the list of rooms.

io.on("connection", (socket) => {
  socket.join("room 237");
  
  console.log(socket.rooms); // Set { <socket.id>, "room 237" }

  socket.join(["room 237", "room 238"]);

  io.to("room 237").emit("a new user has joined the room"); // broadcast to everyone in the room
});

The mechanics of joining rooms are handled by the Adapter that has been configured (see Server#adapter above), defaulting to socket.io-adapter.

For your convenience, each socket automatically joins a room identified by its id (see Socket#id). This makes it easy to broadcast messages to other sockets:

io.on("connection", (socket) => {
  socket.on("say to someone", (id, msg) => {
    // send a private message to the socket with the given id
    socket.to(id).emit("my message", msg);
  });
});

socket.leave(room)

  • room (String)
  • Returns void | Promise

Removes the socket from the given room.

io.on("connection", (socket) => {
  socket.leave("room 237");

  io.to("room 237").emit(`user ${socket.id} has left the room`);
});

Rooms are left automatically upon disconnection.

socket.to(room)

History
Version Changes
v4.0.0 Allow to pass an array of rooms.
v1.0.0 Initial implementation.
  • room (string) | (string[])
  • Returns Socket for chaining

Sets a modifier for a subsequent event emission that the event will only be broadcast to clients that have joined the given room (the socket itself being excluded).

To emit to multiple rooms, you can call to several times.

io.on("connection", (socket) => {

  // to one room
  socket.to("others").emit("an event", { some: "data" });

  // to multiple rooms
  socket.to("room1").to("room2").emit("hello");

  // or with an array
  socket.to(["room1", "room2"]).emit("hello");

  // a private message to another socket
  socket.to(/* another socket id */).emit("hey");

  // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
});

Note: acknowledgements are not supported when broadcasting.

socket.in(room)

Added in v1.0.0

Synonym of socket.to(room).

socket.except(rooms)

Added in v4.0.0

  • rooms (string) | (string[])
  • Returns BroadcastOperator

Sets a modifier for a subsequent event emission that the event will only be broadcast to clients that have not joined the given rooms (the socket itself being excluded).

// to all clients except the ones in "room1" and the sender
socket.broadcast.except("room1").emit(/* ... */);

// same as above
socket.except("room1").emit(/* ... */);

// to all clients in "room4" except the ones in "room5" and the sender
socket.to("room4").except("room5").emit(/* ... */);

socket.compress(value)

  • value (Boolean) whether to following packet will be compressed
  • Returns Socket for chaining

Sets a modifier for a subsequent event emission that the event data will only be compressed if the value is true. Defaults to true when you don’t call the method.

io.on("connection", (socket) => {
  socket.compress(false).emit("uncompressed", "that's rough");
});

socket.disconnect(close)

  • close (Boolean) whether to close the underlying connection
  • Returns Socket

Disconnects this socket. If value of close is true, closes the underlying connection. Otherwise, it just disconnects the namespace.

io.on("connection", (socket) => {
  setTimeout(() => socket.disconnect(true), 5000);
});

Flag: ‘broadcast’

Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.

io.on("connection", (socket) => {
  socket.broadcast.emit("an event", { some: "data" }); // everyone gets it but the sender
});

Flag: ‘volatile’

Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because they’re connected through long polling and is in the middle of a request-response cycle).

io.on("connection", (socket) => {
  socket.volatile.emit("an event", { some: "data" }); // the client may or may not receive it
});

Event: ‘disconnect’

  • reason (String) the reason of the disconnection (either client or server-side)

Fired upon disconnection.

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

Possible reasons:

Reason Description
server namespace disconnect The socket was forcefully disconnected with socket.disconnect()
client namespace disconnect The client has manually disconnected the socket using socket.disconnect()
server shutting down The server is, well, shutting down
ping timeout The client did not send a PONG packet in the pingTimeout delay
transport close The connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
transport error The connection has encountered an error

Event: ‘disconnecting’

  • reason (String) the reason of the disconnection (either client or server-side)

Fired when the client is going to be disconnected (but hasn’t left its rooms yet).

io.on("connection", (socket) => {
  socket.on("disconnecting", (reason) => {
    console.log(socket.rooms); // Set { ... }
  });
});

Note: those events, along with connect, connect_error, newListener and removeListener, are special events that shouldn’t be used in your application:

// BAD, will throw an error
socket.emit("disconnect");

Client

The Client class represents an incoming transport (engine.io) connection. A Client can be associated with many multiplexed Sockets that belong to different Namespaces.

client.conn

  • (engine.Socket)

A reference to the underlying engine.io Socket connection.

client.request

  • (Request)

A getter proxy that returns the reference to the request that originated the engine.io connection. Useful for accessing request headers such as Cookie or User-Agent.

© 2014–2021 Automattic
Licensed under the MIT License.
https://socket.io/docs/v4/server-api