如何捕获WebSocket连接中断?

问题描述:

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

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.

这是我试图实现的代码示例,但是没有什么我能弄清楚会抓住错误并允许我优雅地处理它。

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.

看看代码: 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.

我在这里做错了,还是因为连接在JS脚本范围之外运行而不可能?

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?

任何输入都会有帮助。

谢谢!

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

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

参见: 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.