The Socket instance (client-side)
Each new connection is assigned a random 20-characters identifier.
This identifier is synced with the value on the server-side.
This attribute describes whether the socket is currently connected to the server.
socket.on("connect", () => {
console.log(socket.connected); // true
});
socket.on("disconnect", () => {
console.log(socket.connected); // false
});
The Socket instance emits three special events:
socket.io.on("reconnection_attempt", () => {
// ...
});
socket.io.on("reconnect", () => {
// ...
});
More information can be found in the migration guide.
This event is fired by the Socket instance upon connection and reconnection.
Please note that you shouldn’t register event handlers in the connect
handler itself, as a new handler will be registered every time the Socket reconnects:
// BAD
socket.on("connect", () => {
socket.on("data", () => { /* ... */ });
});
// GOOD
socket.on("connect", () => {
// ...
});
socket.on("data", () => { /* ... */ });
This event is fired when:
- the low-level connection cannot be established
- the connection is denied by the server in a
In the first case, the Socket will automatically try to reconnect, after a given delay.
// either by directly modifying the `auth` attribute
socket.on("connect_error", () => {
socket.auth.token = "abcd";
socket.connect();
});
// or if the `auth` attribute is a function
const socket = io({
auth: (cb) => {
cb(localStorage.getItem("token"));
}
});
socket.on("connect_error", () => {
setTimeout(() => {
socket.connect();
}, 1000);
});
This event is fired upon disconnection.
Here is the list of possible reasons:
In the first two cases (explicit disconnection), the client will not try to reconnect and you need to manually call socket.connect()
.
In all other cases, the client will wait for a small and then try to reconnect:
Note: those events, along with disconnecting
, newListener
and , are special events that shouldn’t be used in your application:
// BAD, will throw an error
socket.emit("disconnect");
Caught a mistake? Edit this page on GitHub