javascriptsocketswebsockethandshakealchemy

JavaScript websocket error


Sometimes, when I reload the page, it appears an error:
WebSocket connection to 'ws://127.0.0.1:45/' failed: Connection closed before receiving a handshake response
I'm using Alchemy Websocket library for C#. And I can only fix deleting the cookies and local storage. How can I fix that?


Solution

  • Ok, define your socket as a "global variable", presumably at the top of the document. Now this socket variable is available in the whole document. When a user clicks the x on the tab/browser window (or reloads the page), you want the window.onunload event to fire, so define that somewhere - and call the close method of your global socket variable.

        var _socket = new WebSocket("ws://127.0.0.1/example");
    
        window.onunload = function () {
    
            _socket.close();
        }