WebSocket连接超时 [英] WebSocket Connection timeout

查看:1168
本文介绍了WebSocket连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现failafe websocket包装器。而我遇到的问题是处理超时错误。逻辑应该是:如果套接字在$ timeoutInMiliseconds期间没有打开 - 它必须关闭并重新打开$ N次。

I am trying to implement failsafe websocket wrapper. And the problem that I have is dealing with timeout errors. The logic should be: if the socket is not opened during $timeoutInMiliseconds - it must be closed and reopened $N times.

我写的是这样的。

var maxReconects = 0;
var ws = new WebSocket(url);
var onCloseHandler = function() {
    if ( maxReconects < N ) {
        maxReconects++;
        // construct new Websocket 
        ....
    }
};
ws.onclose = onCloseHandler;
var timeout = setTimeout(function() {
                console.log("Socket connection timeout",ws.readyState);
                timedOut = true;
                ws.close();  <--- ws.readyState is 0 here 
                timedOut = false;
},timeoutInMiliseconds); 

但问题是正确处理超时websockets - 如果我试图关闭非连接套接字我收到警告in chrome:

But the problem is handling timeout websockets right way - if i am trying to close nonconnected socket I receive warning in chrome :

WebSocket连接到'ws://127.0.0.1:9010 / timeout'失败:WebSocket在建立连接之前关闭。

"WebSocket connection to 'ws://127.0.0.1:9010/timeout' failed: WebSocket is closed before the connection is established."

我不知道如何避免它 - ws接口没有中止功能。

And I have no Idea how to avoid it - ws interface has no abort function .

我试过的另一个方法如果它没有连接,则不会在超时时关闭套接字,只是将其标记为未使用更多并在接收到readyState多于一个时将其关闭 - 但它可能产生可能的泄漏,并且对于这样简单的任务而言很复杂。

The other aproach I have tried is not to close socket on timeout if it nonconnected but just mark it as not used more and close it if it receive readyState more than one - but it can produce possible leaks , and to complicated for such simple task.

推荐答案

我为打开带有超时和重试的websocket failafe 编写了以下代码,请参阅代码中的注释以获取更多详细信息。

I've written the following code for opening a websocket failsafe with timeout and retries, see comments in code for more details.

用法 - 打开一个包含5000毫秒超时和10次重试(最大)的websocket:

Usage - opening a websocket with 5000ms timeout and 10 retries (maximum):

initWebsocket('ws:\\localhost:8090', null, 5000, 10).then(function(socket){
    console.log('socket initialized!');
    //do something with socket...

    //if you want to use the socket later again and assure that it is still open:
    initWebsocket('ws:\\localhost:8090', socket, 5000, 10).then(function(socket){
        //if socket is still open, you are using the same "socket" object here
        //if socket was closed, you are using a new opened "socket" object
    }

}, function(){
    console.log('init of socket failed!');
});

方法 initWebsocket()在库或类似物中定义的地方:

method initWebsocket() somewhere defined in a library or similar:

/**
 * inits a websocket by a given url, returned promise resolves with initialized websocket, rejects after failure/timeout.
 *
 * @param url the websocket url to init
 * @param existingWebsocket if passed and this passed websocket is already open, this existingWebsocket is resolved, no additional websocket is opened
 * @param timeoutMs the timeout in milliseconds for opening the websocket
 * @param numberOfRetries the number of times initializing the socket should be retried, if not specified or 0, no retries are made
 *        and a failure/timeout causes rejection of the returned promise
 * @return {Promise}
 */
function initWebsocket(url, existingWebsocket, timeoutMs, numberOfRetries) {
    timeoutMs = timeoutMs ? timeoutMs : 1500;
    numberOfRetries = numberOfRetries ? numberOfRetries : 0;
    var hasReturned = false;
    var promise = new Promise((resolve, reject) => {
        setTimeout(function () {
            if(!hasReturned) {
                console.info('opening websocket timed out: ' + url);
                rejectInternal();
            }
        }, timeoutMs);
        if (!existingWebsocket || existingWebsocket.readyState != existingWebsocket.OPEN) {
            if (existingWebsocket) {
                existingWebsocket.close();
            }
            var websocket = new WebSocket(url);
            websocket.onopen = function () {
                if(hasReturned) {
                    websocket.close();
                } else {
                    console.info('websocket to opened! url: ' + url);
                    resolve(websocket);
                }
            };
            websocket.onclose = function () {
                console.info('websocket closed! url: ' + url);
                rejectInternal();
            };
            websocket.onerror = function () {
                console.info('websocket error! url: ' + url);
                rejectInternal();
            };
        } else {
            resolve(existingWebsocket);
        }

        function rejectInternal() {
            if(numberOfRetries <= 0) {
                reject();
            } else if(!hasReturned) {
                hasReturned = true;
                console.info('retrying connection to websocket! url: ' + url + ', remaining retries: ' + (numberOfRetries-1));
                initWebsocket(url, null, timeoutMs, numberOfRetries-1).then(resolve, reject);
            }
        }
    });
    promise.then(function () {hasReturned = true;}, function () {hasReturned = true;});
    return promise;
};

更好的解决方案是将功能封装在自己的类 FailsafeWebsocket 或者无论如何。然而,这个解决方案在我的项目中已经足够 - 也许它也可以帮助其他人。

a better solution would be encapsulating the functionality in an own class FailsafeWebsocket or whatsoever. However this solution is sufficient in my project - maybe it helps somebody else too.

这篇关于WebSocket连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆