【问题标题】:How to reconnect to socket after disconnecting in html5如何在html5中断开连接后重新连接到套接字
【发布时间】:2015-10-24 22:07:41
【问题描述】:

我正在使用 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;
...
}

但是没有用。

有什么想法吗?

【问题讨论】:

标签: javascript html sockets websocket


【解决方案1】:

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

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

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

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

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

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

    这意味着你的代码就像一个原子单元——在你的代码完成运行之前什么都不会发生,也不会发生任何变化。

  • 因为建立连接可能需要一段时间,所以 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); 

【讨论】:

    猜你喜欢
    • 2021-11-26
    • 2019-03-05
    • 1970-01-01
    • 2021-12-09
    • 2012-08-07
    • 2016-03-08
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多