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

查看:3421
本文介绍了正确关闭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.

推荐答案

根据协议规范 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天全站免登陆