【问题标题】:Closing HTML5 Web Sockets关闭 HTML5 Web 套接字
【发布时间】:2013-11-04 20:43:26
【问题描述】:

HTML5 Web Sockets behave strangely 如果用户正在刷新页面或导航 远离它。在页面重新加载期间,网络服务器和浏览器之间的套接字连接似乎保持打开状态,如果页面在浏览器中重新加载,则在 Firefox 和 Chrome 中关闭。这意味着它只在浏览器和服务器之间建立连接每秒钟工作一次,因为 套接字在重新加载时被浏览器关闭。 Firefox 的 Firebug 控制台中的错误消息是“与 ws://.../websocket 的连接在页面加载时被中断”。显然,当页面重新加载时 websocket 连接仍然打开,这意味着连接在页面加载期间关闭,而不是每隔一个页面加载打开一次。例如这样读取的日志文件(使用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>

有没有办法在onbeforeunload Javascript 事件中关闭所有打开的套接字和连接? 喜欢(在 Coffeescript 中)..

  window.onbeforeunload = () ->
    close_all_sockets()

【问题讨论】:

    标签: javascript coffeescript websocket


    【解决方案1】:

    这有点棘手,但你可以通过创建一个新的WebSocket,并通过它的协议参数发送应该断开的用户的标识来做到这一点。

    例如:

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

    服务器在收到使用此非标准协议的新连接请求时,必须关闭相应的连接。

    这是我在我的服务器 (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;
        // ........
    }
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多