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

115
Views
Websocket reconnection is long when the server was offline

I'm using this common code for websocket:

ws = null;
let connected = false;
let isConnecting = false;
let timeout = 250;

const extractHostname = function (url) {
    let hostname;
    if (url.indexOf("://") > -1) hostname = url.split("/")[2];
    else hostname = url.split("/")[0];
    hostname = hostname.split(":")[0];
    hostname = hostname.split("?")[0];
    return hostname;
};

const composeWsAddress = function (address) {
    let scheme = "ws";
    if (document.location.protocol === "https:") scheme += "s";
    return scheme + "://" + address + ":8000/ws";
};

const open = function (address) {
    isConnecting = true;

    delete ws;
    ws = new WebSocket(address);
    ws.onopen = onOpen;
    ws.onclose = onClose;
    ws.onmessage = onMessage;
    ws.onerror = onError;
};

const close = function () {
    if (ws)  ws.close();
    connected = false;
    isConnecting = false;
};

let onOpen = function() {
    connected = true;
    isConnecting = false;
    timeout = 250;
};

let onClose = function() {
    ws = null;
    isConnecting = false;
    setTimeout (reconnect, 1000);
};

let onMessage = function(event) {
};

let onError = function(event) {
    ws = null;
    isConnecting = false;
    setTimeout (reconnect, 1000);
};

WebSocketClient = {
    init: function() {    
    }
};

function reconnect() {
    if (isConnecting) return;
    const address = composeWsAddress(extractHostname(location.href));
    open(address);
}

$(function() {
    WebSocketClient.init();
    reconnect();
});
  • If I start the server and then open my web page the connection is almost immediate.

  • If I keep the web page open, stop the server and after a while I restart it the connection is still quite fast (1-2 seconds maximum).

  • But if I keep the web page open, stop the server for several minutes, when I restart it the connection requires a lot of time - even 2-3 minutes!

What's wrong in my approach?

about 4 years ago · Juan Pablo Isaza
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!