在html5中断开连接后如何重新连接到套接字

时间:2015-10-24 22:07:42

标签: javascript html5 sockets websocket

我正在使用HTML5套接字函数来建立与我的服务器的套接字连接。 HTML5具有以下功能来处理断开连接

Socket.onclose = function()
{
...
}
Socket.onerror = function()
{
...
}

我的问题是,如何在onclose函数执行后尝试重新连接?我尝试在其中放置一个while循环,如

ws.onclose = function()
{
  While(conn==0)
  {
    ws = new WebSocket("ws://example.com");
  }
}

ws.onopen = function()
{
conn=1;
...
}

但是没有用。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

以下是Plezi websocket framework附带的脚本...这是相当基本的,但它适用于我在其上使用的浏览器(Safari,Chrome和FireFox)。

诀窍是在没有循环的情况下利用onclose方法。

即使websocket从未打开且无法建立连接,也会调用onclose方法(不调用onopen)。

onclose内启动重新连接就足够了。

编写循环或条件审核不仅会失败,还会暂停页面上的所有脚本。请允许我解释一下:

  • Javascript 单线程。再说一遍:它是一个基于偶数/任务的单线程环境。

    这意味着您的代码就像 atomic 单元一样 - 没有任何反应,在代码完成运行之前没有任何变化。

  • 因为连接可能需要一段时间来建立,所以new WebSocket被设计(并且理所当然地)作为异步函数。

    这就是为什么你可以在创建事件后定义onopen事件回调。

  • 只有在当前任务/事件完成后才会尝试新的websocket连接 ......

    ...所以一个循环会让你永远陷入等待 无法执行 的任务,直到你的代码停止运行......

回到手头的问题,这是代码。如果您有任何改进意见,请告诉我们:

// Your websocket URI should be an absolute path. The following sets the base URI.
// remember to update to the specific controller's path to your websocket URI.
var ws_controller_path = window.location.pathname; // change to '/controller/path'
var ws_uri = (window.location.protocol.match(/https/) ? 'wss' : 'ws') + '://' + window.document.location.host + ws_controller_path
// websocket variable.
var websocket = NaN
// count failed attempts
var websocket_fail_count = 0
// to limit failed reconnection attempts, set this to a number.
var websocket_fail_limit = NaN
// to offer more or less space between reconnection attempts, set this interval in miliseconds.
var websocket_reconnect_interval = 250

function init_websocket()
{
    if(websocket && websocket.readyState == 1) return true; // console.log('no need to renew socket connection');
    websocket = new WebSocket(ws_uri);
    websocket.onopen = function(e) {
        // reset the count.
        websocket_fail_count = 0
        // what do you want to do now?
    };

    websocket.onclose = function(e) {
        // If the websocket repeatedly you probably want to reopen the websocket if it closes
        if(!isNaN(websocket_fail_limit) && websocket_fail_count >= websocket_fail_limit) {
            // What to do if we can't reconnect so many times?
            return
        };
        // you probably want to reopen the websocket if it closes.
        if(isNaN(websocket_fail_limit) || (websocket_fail_count <= websocket_fail_limit) ) {
            // update the count
            websocket_fail_count += 1;
            // try to reconect
            setTimeout( init_websocket, websocket_reconnect_interval);
        };
    };
    websocket.onerror = function(e) {
        // update the count.
        websocket_fail_count += 1
        // what do you want to do now?
    };
    websocket.onmessage = function(e) {
        // what do you want to do now?
        console.log(e.data);
        // to use JSON, use:
        // var msg = JSON.parse(e.data); // remember to use JSON also in your Plezi controller.
    };
}
// setup the websocket connection once the page is done loading
window.addEventListener("load", init_websocket, false);