0

HTML5 Web Sockets behave strangely if users are refreshing the page, or navigating away from it. During reloading of the page, the socket connections between webserver and browser seem to stay open, and are closed if the page reloads in the browser, in both Firefox and Chrome. This means it works only every second time to establish a connection between browser and server, because the socket is closed by the browser on reload. The error message in the Firebug console from Firefox is "The connection to ws://.../websocket" was interrupted while the page was loading". So apparently the websocket connection is still open when the page is reloaded, which means the connection is closed during page load instead of opened every second page load. Log files read for instance like this (created with the Websocket-Rails gem)

==> first page load
[ConnectionManager] Connection opened: #<Connection::fef69428febee72f4830>
[Channel] #<Connection::fef69428febee72f4830> subscribed to channel xyz

==> second page load
[Channel] #<Connection::dfc4b33090b95826e08e> unsubscribed from channel xyz
[ConnectionManager] Connection closed: #<Connection::dfc4b33090b95826e08e>

Is there are way to close all open sockets and connections in the onbeforeunload Javascript event, something like (in Coffeescript)..

  window.onbeforeunload = () ->
    close_all_sockets()
Community
  • 1
  • 1
0x4a6f4672
  • 27,297
  • 17
  • 103
  • 140

1 Answers1

1

It is a bit tricky, but you can do it by creating a new WebSocket, and sending the identification of the user who should be disconnected through its protocol parameter.

For instance :

window.onbeforeunload = function () {
    new WebSocket(myWebSocket.url, myUserName + "*" + myPassword);
}

The server must close the appropriate connection when it receives a new connection request with this non standard protocol.

This is what I've done in the handshake code of my server (C#) :

switch (handshakeKey)
{
    // ..........
    case "Sec-WebSocket-Protocol":
        string[] infos = handshakeValue.Split('*');
        if (infos.Length == 2)
        {
            Guest aguest = server.FindGuest(infos[0]);
            if (aguest != null && aguest.password == infos[1]) server.RemoveGuest(aguest);
            // The removeGuest function closes its socket            }
        TCPClient.Close(); // close the temporary connection
        break;
    // ........
}

Hope this helps.

Xodrow
  • 315
  • 1
  • 7