2

切断されたときに 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 回再接続を試みます。そうしようとしている間、Google Chromeコンソールで監視したように、6つの接続が開きます(接続に6回失敗した場合)。誰かがここで私が間違っていることを提案できますか、それとも私のアプローチに何か問題がありますか? とても役に立ちます。

4

0 に答える 0