Socket.io-client connection error: websocket error

8.9k Views Asked by At

Previously, I was getting the output "xhr poll error" with the code:

import { io } from "socket.io-client";

const socket = io("https://socket.io/docs/v4", {
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax: 5000,
    reconnectionAttempts: 3
});

socket.on('connect_error', function(error) {
    console.log(error.message);
});

With a bit of research, this was "resolved" by adding "transports: ['websocket']". Here's my current code:

import { io } from "socket.io-client";

const socket = io("https://socket.io/docs/v4", {
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax: 5000,
    reconnectionAttempts: 3,
    transports: ['websocket']
});

socket.on('connect_error', function(error) {
    console.log(error.message);
});

Unfortunately, this doesn't really resolve my problem because now I get the following output: websocket error.

Other things I've tried: specifying the port after the URL and setting rejectUnauthorized to false. (both giving me the same websocket error.

I'm a bit stumped on what to do next, and it'd be nice to hear some of you guys' feedback!

Socket.io-client version: 4.5.1

3

There are 3 best solutions below

0
On BEST ANSWER

By default, the client will try to establish a WebSocket connection if possible and will fall back on HTTP long polling if not, which explains why the first change you mentioned resolved the polling error, but now you have a websocket error.

If it's attempting to reconnect automatically, you might need to enable CORS or set credentials. If it's not, you should try manually reconnecting after a timeout with socket.connect()

1
On

For those that may experience this problem in the future (using expo react app) i was getting "websocket error" because my app couldnt reach my express server at http://localhost:3000 i had to switch 'localhost' for my local pc ip.

(how to get yours -> https://www.avast.com/c-how-to-find-ip-address#:~:text=You%20can%20find%20your%20local,listed%20next%20to%20IPv4%20address.)

All i had to do in my server was add

const httpServer = createServer(app);

httpServer.listen(PORT, 'your.local.ip', () => {
  console.log(`Server started on port ${PORT}`);
});

const io = new Server(httpServer, { cors: { origin: '*' } });

and in my client do

import { io } from 'socket.io-client';

export const socket = io('http://your.local.ip:3000', { transports: ['websocket'] });

socket.on('connect_error', (err) => {
  console.log(err.message);
});

Note that this is only the solution for local development and not a production environment

1
On

It might be a version compatibility issue with Client and Server libraries. I was having similar issues and was able to resolve them by adding https://socket.io/docs/v4/server-options/#alloweio3 after looking at https://socket.io/docs/v4/client-installation/#version-compatibility