我正在尝试构建一个逻辑,我尝试在断开连接时重新连接websocket连接。我写了以下逻辑。
var webSocketObj = null;
var countForWebSocketReconnection = 0;
var intervalIdForWebSocket = "";
function webSocketConnection (message_arr) {
if ("WebSocket" in window) {
try {
webSocketObj.onopen = null;
webSocketObj.onmessage = null;
webSocketObj.onclose = null;
webSocketObj.onerror = null;
webSocketObj.close();
} catch (e) {
console.log('try/catch around location update'+e);
} finally {
webSocketObj = new WebSocket(webSocketUrl);
webSocketObj.onopen = function() {
webSocketOpen(message_arr);
};
webSocketObj.onmessage = function (evt) {
websocketMessage(evt);
}
webSocketObj.onclose = function() {
if(countForWebSocketReconnection>=6){
alert("Web-socket connection is terminated by the browser. Please reload the page.");
clearTimeout(intervalIdForWebSocket );
intervalIdForWebSocket = "";
} else {
monitorIntervalIdForWebSocket = setTimeout(function(){
webSocketObj.onopen = null;
webSocketObj.onmessage = null;
webSocketObj.onclose = null;
webSocketObj.onerror = null;
webSocketObj.close();
webSocketConnection(message_arr);
countForWebSocketReconnection++;
}, 10000);
}
}
webSocketObj.onerror = function(evt) {
webSocketOnError(evt);
}
}
} else {
}
}
如果有任何断开连接,它会尝试重新连接6次。在尝试这样做时,它会打开6个连接(如果6个连接尝试失败)我在谷歌Chrome控制台上监控。有人可以在这里建议我做错了什么或者我的方法有问题吗?这将非常有帮助。