Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Socket io, Try multiple URLs to establish connection after "connect_error"

I have an app with divided code (client / server). On the client side, I'd like socket io to attempt multiple URLs (one at a time) until it connects successfully.

Here's my code:

const BAD_HOST = "http://localhost:8081";
const LOCAL_HOST = "http://localhost:8080";
const SOCKET_CONFIG = {
  upgrade: false,
  transports: ["websocket"],
  auth: { ... }, // Trimmed for brevity
  extraHeaders: { ... }, // Trimmed for brevity
};

let socket = io(BAD_HOST, SOCKET_CONFIG); // This connects fine when I use LOCAL_HOST

socket.on("connect_error", (err) => {
  console.log(err); 
  socket = io(LOCAL_HOST, SOCKET_CONFIG); // DOES NOT WORK
});

socket.on("connect", () => { ... } // Trimmed for brevity

In short, when I try to reassign the value for socket to a new io connection, it seems to retain the old, failed connection. My browser continues to throw 'connect_error' messages from the bad url: WebSocket connection to 'ws://localhost:8081/socket.io/?EIO=4&transport=websocket' failed:

I checked but couldn't find any official documentation on this question.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I think an approach is already discussed here: https://stackoverflow.com/a/22722710/656708

Essentially you have an array of URLs, which in your case would be:

const socketServerURLs = ["http://localhost:8081","http://localhost:8080"];

and then iterate over them, trying to initiate a socket connection, like this:

// something along these lines
socketServerURLs.forEach((url) => { 
  // ...
  socket.connect(url, socketConfiguration, (client) => {});
  // ...
}

Then again, I don't know what a BAD_HOST entails. Assuming that you mean that a connection to that host failed, how would you know that without actually trying to connect to it?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!