Here how my code looks like:
var ws = null;
var _open = function(address) {
ws = new WebSocket(address);
ws.onopen = onOpen;
ws.onclose = onClose;
ws.onmessage = onMessage;
ws.onerror = onError;
};
var close = function() {
if (ws) ws.close();
};
var onOpen = function() {
// do something
};
var onClose = function() {
ws = null;
retry();
};
var onError = function(event) {
ws = null;
retry();
};
var onMessage = function(event) {
// do something
};
var retry = function() {
setTimeout(function() {
// extract what I need from location.href
var address = composeWsAddress(extractHostname(location.href));
_open(address);
}, 3000);
};
WebSocketClient = {
init: function() {
var address = composeWsAddress(extractHostname(location.href));
_open(address);
}
};
It should work in this way:
- at start (
init
) it tries to connect - if fails (
onError
) it tries again after 3 s - if succeeds (
onOpen
) and then the connection closes (onClose
) it tries again after 3 s
It works but on the WebSocket server I receive a number of new connections how many times they failed. For example, I launch my client application and after 30 s start the server. Now I have about 10 connections opened (one every 3 s).
Here I read I should not take care of "delete" each instance created by new WebSocket
. Anyway I set it to null
when the connection fails or closes.
So why it still keeps the old instances?