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?