socket.io
socket.io copied to clipboard
Event connect_error handling
Describe the bug
The docs https://socket.io/docs/v4/client-socket-instance/#connect_error says:
This event is fired when:
1) the low-level connection cannot be established
2) the connection is denied by the server in a middleware function
In the first case, the Socket will automatically try to reconnect, after a [given delay](https://socket.io/docs/v4/client-options/#reconnectiondelay).
In the latter case, you need to manually reconnect. You might need to update the credentials.
I'm trying to make the code to auto reconnect in both cases.
Inside the connect_error handler there is no way of knowing if it was called because of case 1) or 2). So, there is no way of knowing if it will auto reconnect or it would not.
To handle both cases I tried a code like in the docs:
socket.on("connect_error", () => {
socket.connect();
});
But this causes the auto reconnect in case 1) the low-level connection cannot be established to stop after two attempts!
To Reproduce
Socket.IO client version: 4.5.4
Client
import { io } from "socket.io-client";
const socket = io("ws://localhost:3000/", {});
socket.on("connect", () => {
console.log(`connect ${socket.id}`);
});
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
socket.connect();
});
socket.on("disconnect", (reason) => {
console.log(`disconnect due to ${reason}`);
});
Expected behavior
The socket to keep trying to connect.
So, there must be an increasing number of messages connect_error due to
The actual behaviour is: There are only TWO messages:
connect_error due to xhr poll error
connect_error due to xhr poll error
As a workaround I use a code like this. It does not break the auto reconnect.
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
setTimeout(() => {
socket.connect();
}, 0);
});
Also the "connect_error" argument err is not well documented. After some logging and debugging I found that a code like this could do the job:
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
if (err.type === 'TransportError') {
// the Socket will automatically try to reconnect
} else {
socket.connect();
}
});
Anyway I think the lib or the docs should be fixed.
Platform:
- OS: MacOS 13.1