正确关闭 WebSocket(HTML5、Javascript) [英] Closing WebSocket correctly (HTML5, Javascript)

查看:615
本文介绍了正确关闭 WebSocket(HTML5、Javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩 HTML5 WebSockets.我想知道,如何优雅地关闭连接?例如,如果用户刷新页面或关闭浏览器会发生什么?

I am playing around with HTML5 WebSockets. I was wondering, how do I close the connection gracefully? Like, what happens if user refreshes the page, or just closes the browser?

当用户在没有调用 websocket.close() 的情况下刷新页面时,会出现一种奇怪的行为 - 当他们在刷新后返回时,它将命中 websocket.onclose活动.

There is a weird behavior when a user just refresh the page without calling websocket.close() - when they return after the refresh it will hit the websocket.onclose event.

推荐答案

根据 protocol spec v76(目前支持的浏览器实现的版本):

According to the protocol spec v76 (which is the version that browser with current support implement):

为了干净地关闭连接,一个只包含 0xFF 字节的帧后跟一个 0x00 字节是从一个对等体发送来询问另一个对等体关闭连接.

To close the connection cleanly, a frame consisting of just a 0xFF byte followed by a 0x00 byte is sent from one peer to ask that the other peer close the connection.

如果您正在编写服务器,则应确保在服务器关闭客户端连接时发送关闭帧.正常的 TCP 套接字关闭方法有时会很慢,导致应用程序认为连接仍然打开,即使它没有打开.

If you are writing a server, you should make sure to send a close frame when the server closes a client connection. The normal TCP socket close method can sometimes be slow and cause applications to think the connection is still open even when it's not.

当您关闭或重新加载页面时,浏览器应该真正为您执行此操作.但是,您可以通过捕获 beforeunload 事件来确保发送关闭帧:

The browser should really do this for you when you close or reload the page. However, you can make sure a close frame is sent by doing capturing the beforeunload event:

window.onbeforeunload = function() {
    websocket.onclose = function () {}; // disable onclose handler first
    websocket.close();
};

我不确定页面刷新后如何获得 onclose 事件.一旦页面重新加载,websocket 对象(带有 onclose 处理程序)将不再存在.如果您在页面加载时立即尝试在您的页面上建立 WebSocket 连接,那么您可能会遇到一个问题,即服务器在旧连接断开后很快拒绝新连接(或浏览器未准备好)在您尝试连接时建立连接)并且您将收到新 websocket 对象的 onclose 事件.

I'm not sure how you can be getting an onclose event after the page is refreshed. The websocket object (with the onclose handler) will no longer exist once the page reloads. If you are immediately trying to establish a WebSocket connection on your page as the page loads, then you may be running into an issue where the server is refusing a new connection so soon after the old one has disconnected (or the browser isn't ready to make connections at the point you are trying to connect) and you are getting an onclose event for the new websocket object.

这篇关于正确关闭 WebSocket(HTML5、Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆