How do I catch a WebSocket connection interruption?

前端 未结 2 416
天命终不由人
天命终不由人 2020-12-31 11:07

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 ag

相关标签:
2条回答
  • 2020-12-31 11:40

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

    See: 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.

    0 讨论(0)
  • 2020-12-31 11:41

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

    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.

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

    Solution (not answer directly to the answer, 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.

    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

    Define transport types on the client side

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

    0 讨论(0)
提交回复
热议问题