javascript 如何捕获 WebSocket 连接中断?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13616960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:17:56  来源:igfitidea点击:

How do I catch a WebSocket connection interruption?

javascriptwebsocket

提问by Zach

In Firefox (at least), if you hit ESC, then it will close all open WebSockets connections. I need to capture that disconnection and try to re-connect once it's available again.

在 Firefox 中(至少),如果您按 ESC,它将关闭所有打开的 WebSockets 连接。我需要捕获该断开连接,并在它再次可用后尝试重新连接。

Here's an example of the code I've tried to implement, but nothing I can figure out will catch the error and allow me to handle it gracefully.

这是我尝试实现的代码示例,但我无法弄清楚可以捕获错误并允许我优雅地处理它。

Have a look at the code: http://jsfiddle.net/w5aAK/

看看代码:http: //jsfiddle.net/w5aAK/

var url = "ws://echo.websocket.org";
    try {
        socket = window['MozWebSocket'] ? new MozWebSocket(url) : new WebSocket(url);
        socket.onopen = function(){
            console.log('Socket is now open.');
        };
        socket.onerror = function (error) {
            console.error('There was an un-identified Web Socket error');
        };
        socket.onmessage = function (message) {
            console.info("Message: %o", message.data);
        };
    } catch (e) {
        console.error('Sorry, the web socket at "%s" is un-available', url);
    }

setTimeout(function(){
    socket.send("Hello World");
}, 1000);

Turn on your console and watch the output.

打开控制台并观察输出。

Am I doing something wrong here, or is it just not possible because the connection is running outside of the scope of the JS script?

我在这里做错了什么,还是因为连接在 JS 脚本的范围之外运行而无法实现?

Any input would be helpful.

任何输入都会有所帮助。

Thanks!

谢谢!

采纳答案by leggetter

You can attach a handler to the socket.oncloseevent. It will be called when you hit ESC and the connection is interrupted.

您可以将处理程序附加到socket.onclose事件。当您按下 ESC 并且连接中断时,它将被调用。

See: http://jsfiddle.net/w5aAK/1/

见:http: //jsfiddle.net/w5aAK/1/

One problem that you can't get around at the moment is the interrupted error being output to the console. There's no way of capturing that at the moment I'm afraid.

您目前无法解决的一个问题是输出到控制台的中断错误。恐怕目前没有办法捕捉到这一点。

回答by Lukas Liesis

You can't catch it and it's not your fault. It's FireFox bug. Vote for it here:

你抓不到它,这不是你的错。这是火狐的bug。在这里投票:

https://bugzilla.mozilla.org/show_bug.cgi?id=712329

https://bugzilla.mozilla.org/show_bug.cgi?id=712329

I personally tried all kind of solutions:

我个人尝试了各种解决方案:

event handlers onunload onbeforeunload onclose try..catch some js error handling 3rd party services etc.

事件处理程序 onunload onbeforeunload onclose try..catch 一些 js 错误处理 3rd 方服务等。

You can log to console your socket, it's closed before unload, but FF thinks different.. :(

您可以登录以控制台您的套接字,它在卸载之前已关闭,但 FF 认为不同.. :(

Solution (not answer directly to theanswer, but it works):

解决方案(不直接回答答案,但它的工作原理):

It's a bug, so you can't catch, but this info is not Solution. After all kind of crazy workarounds and tries to catch that bug, i finally found this working. If you use socket.io to work with WebScokets it can work with different transport technologies. xhr-polling works with Firefox.

这是一个错误,因此您无法捕获,但此信息不是Solution。经过各种疯狂的变通方法并尝试捕获该错误后,我终于发现此方法有效。如果您使用 socket.io 与 WebScokets 一起工作,它可以与不同的传输技术一起工作。xhr-polling 适用于 Firefox。

if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x     or Firefox x.x (ignoring remaining digits);
    socket = io.connect('//' + node_server + '/', {
        transports: ['polling']
    });
} else {
    socket = io.connect('//' + node_server + '/');
}

What helped me - might help you too:

什么对我有帮助 - 也可能对你有帮助:

Web Socket support in Node.js/Socket.io for older browser

Node.js/Socket.io 中对旧浏览器的 Web Socket 支持

Define transport types on the client side

在客户端定义传输类型

socket.io doens't work with transports: [ 'xhr-polling' ]

socket.io 不适用于传输:['xhr-polling']