Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda