Won't switch to polling transport when Websocket transport failed
Describe the bug
I'm trying to connect with websocket transport first and if it fails I was hoping socketio would switch to long-polling. But for some reason, it keeps reconnecting with websocket transport and never switches to polling.
To Reproduce
Socket.IO server version: 4.7.2
Server
const { Server } = require("socket.io");
const express = require("express");
const http = require("http");
const server = http.createServer(express());
const io = new Server({
transports: ["polling", "websocket"],
});
io.on("connection", socket => {
console.log("New Connection");
});
io.attach(server);
server.listen(3000);
Socket.IO client version: 4.7.2
Client
import { io } from "socket.io-client";
const socket = io({
transports: ["websocket", "polling"],
});
socket.on("connect_error", err => {
console.log("connect_error", err);
})
Expected behavior Was expecting the transport would switch to long-polling when websocket isn't available.
Platform:
- Device: Firefox 120
- OS: Windows 10
Additional context I disabled websocket by blocking websocket calls using the Firefox request blocking feature. Can be disabled using this TamperMonkey script as well.
Hi!
The order in the transports option matters:
const socket = io("https://example.com", {
transports: ["websocket", "polling"] // use WebSocket first, if available
});
socket.on("connect_error", () => {
// revert to classic upgrade
socket.io.opts.transports = ["polling", "websocket"];
});
Reference: https://socket.io/docs/v4/client-options/#transports
@darrachequesne okay, so if Websocket is blocked by proxy and unable to connect, shouldn't it switch to polling?
Anything? What's the point of having multiple transports if automatic switching doesn't work?
For future readers:
The tryAllTransports option let the client test all transports instead of just the first one:
import { io } from "socket.io-client";
const socket = io({
tryAllTransports: true
});
Reference: https://socket.io/docs/v4/client-options/#transports
Implemented in https://github.com/socketio/engine.io-client/commit/579b243e89ac7dc58233f9844ef70817364ecf52, included in [email protected] and [email protected].