socket.io-client icon indicating copy to clipboard operation
socket.io-client copied to clipboard

Won't switch to polling transport when Websocket transport failed

Open hassansin opened this issue 2 years ago • 3 comments

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.

image

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.

hassansin avatar Dec 08 '23 08:12 hassansin

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 avatar Dec 08 '23 09:12 darrachequesne

@darrachequesne okay, so if Websocket is blocked by proxy and unable to connect, shouldn't it switch to polling?

hassansin avatar Dec 08 '23 12:12 hassansin

Anything? What's the point of having multiple transports if automatic switching doesn't work?

hassansin avatar Dec 21 '23 07:12 hassansin