4

服务器如何知道在以下场景和其他情况下关闭 HTML5 中的 Web Socket 连接。

  1. 浏览器突然关闭
  2. 浏览器刷新(创建新的 Socket 连接,否则仍将使用现有连接)
  3. 系统突然断电
4

3 回答 3

1

如果客户端在无法通知服务器的情况下退出,则 TCP 实现的基本特征定义了行为。

只要您的应用程序(和主机系统本身)不尝试通过这个断开的连接发送任何数据,主机就不会意识到有问题。因此,从服务器的角度来看,连接可以长时间保持“打开”并分配资源。

但是,在尝试将数据发送到远程端的那一刻,远程端将不会确认检索和 TCP 重传。它涉及一定数量的重复和使用的超时。确切的参数取决于实现(使用的操作系统)。当重传最终失败时,TCP 连接关闭并在服务器端释放资源。这样你就可以

  • 依赖于这样一个事实,即在某些时候您的应用程序可能想要写入丢失的远程端,并且这样做会触发对死连接的检测
  • 通过在应用程序级别使用类似 ping
  • 通过 TCP keepalive 技术在操作系统级别使用类似 ping 的东西。
于 2013-03-07T14:55:47.330 回答
0

The easiest part of your question is the browser refresh part. IE,FF and Chrome will close the opened connection and open a new one. I guess, that any other browser will do the same.

Point 1 and 3 i can only guess: If the client can still close the tcp connection cleanly, the server will immediately recognize that the connection has been closed. If you are using tomcat, the onClose method of the MessageInbound instance will be called.

If the client could not close the tcp connection cleanly, the server will wait for some kind of timeout. The server will definitely timeout fast when it tries to write something to the socket. You could implement a heartbeat mechanism to do this. Websockets seem to have the option of an automatic heartbeat but not all browsers and servers seem to support it.

于 2013-03-01T15:10:52.597 回答
0

如果用户关闭带有打开的 Web 套接字的浏览器选项卡,服务器将不知道该选项卡已立即关闭。但是,正如 Jan-Philip 所说,如果您尝试编写操作将失败并使用错误,因为您知道连接的当前状态。

例如,在使用 nodejs 的 ws 库时,如果您尝试将数据发送到已关闭的 websocket,则会引发异常,例如 [错误:未打开]。他们你知道连接不再存在,你可以做任何需要的清理工作。

于 2015-08-15T00:41:07.897 回答