0

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.

Mark
  • 3,703
  • 6
  • 40
  • 100

0 Answers0