The Socket instance (server-side)
- emitting and events
- broadcasting events
The Socket instance has a few attributes that may be of use in your application:
Each new connection is assigned a random 20-characters identifier.
This identifier is synced with the value on the client-side.
Upon creation, the Socket joins the room identified by its own id, which means you can use it for private messaging:
io.on("connection", socket => {
socket.on("private message", (anotherSocketId, msg) => {
socket.to(anotherSocketId).emit("private message", socket.id, msg);
});
});
Note: you can’t overwrite this identifier, as it is used in several parts of the Socket.IO codebase.
Socket#handshake
Example:
This is a reference to the the Socket is currently in.
io.on("connection", (socket) => {
console.log(socket.rooms); // Set { <socket.id> }
socket.join("room1");
console.log(socket.rooms); // Set { <socket.id>, "room1" }
});
Additional attributes
As long as you do not overwrite any existing attribute, you can attach any attribute to the Socket instance and use it later:
// in a middleware
io.use(async (socket, next) => {
try {
const user = await fetchUser(socket);
socket.user = user;
} catch (e) {
next(new Error("unknown user"));
}
});
io.on("connection", (socket) => {
console.log(socket.user);
// in a listener
socket.on("set username", (username) => {
socket.username = username;
});
});
Those middlewares looks a lot like the usual , except that they are called for each incoming packet:
The next
method can also be called with an error object. In that case, the event will not reach the registered event handlers and an error
event will be emitted instead:
io.on("connection", (socket) => {
socket.use(([event, ...args], next) => {
if (isUnauthorized(event)) {
return next(new Error("unauthorized event"));
}
next();
});
socket.on("error", (err) => {
if (err && err.message === "unauthorized event") {
socket.disconnect();
}
});
});
Events
On the server-side, the Socket instance emits two special events:
This event is fired by the Socket instance upon disconnection.
io.on("connection", (socket) => {
socket.on("disconnect", (reason) => {
// ...
});
});
Here is the list of possible reasons:
disconnecting
This event is similar to disconnect
but is fired a bit earlier, when the Socket#rooms set is not empty yet
Note: those events, along with connect
, connect_error
, newListener
and removeListener
, are special events that shouldn’t be used in your application:
Caught a mistake? Edit this page on