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

133
Visualizações
Assigning new websocket leads to spawining multiple clients

In web application, I'm trying to reconnect to a websocket server if the channel disconnects:

let ws = null;
let connected = false;

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) {
    console.log("connecting...");
    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;
};

var onOpen = function() {
    connected = true;
    console.log("connected!");
};

var onClose = function() {
    ws = null;
    console.log("connection closed!");
    setTimeout(reconnect, 3000);
};

var onMessage = function(event) {
};

var onError = function(event) {
    ws = null;
    console.log("connection error!");
    setTimeout(reconnect, 3000);
};

WebSocketClient = {
    init: function() {

    }
};

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

$(function() {
    WebSocketClient.init();
    reconnect();
});

To test it I follow this procedure:

  1. start the server
  2. run the client code -> it connects
  3. stop the server
  4. the client disconnects and every 3 seconds it tries to reconnect
  5. re-start the server -> it connects again

but the server now says there are a lot of clients connected: one for each failed tentative.

Here I learn there is no need in javascript to "delete" an object created with the new keyword. So I'm not sure where my error is.

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