Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda