- Namespace
- namespace.name
- namespace.sockets
- namespace.adapter
- namespace.to(room)
- namespace.in(room)
- namespace.except(rooms)
- namespace.emit(eventName[, …args])
- namespace.allSockets()
- namespace.use(fn)
- namespace.socketsJoin(rooms)
- namespace.socketsLeave(rooms)
- namespace.disconnectSockets([close])
- namespace.fetchSockets()
- namespace.serverSideEmit(eventName[, …args][, ack])
- Event: ‘connection’
- Event: ‘connect’
- Flag: ‘volatile’
- Flag: ‘local’
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 socket.io-redis@6.1.0
), 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
andnew_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" });