如何清除websocket上的缓冲区? [英] How to clear buffer on websocket?

查看:397
本文介绍了如何清除websocket上的缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎 websocket 在断开连接时正在缓冲消息,并在连接后立即发送.

It seems like websocket is buffering messages when it's disconnected, and sends it as soon as it is connected.

我可以看到 websocket 的 bufferedAmount 正在增加,但它是只读的.

I can see that bufferedAmount of websocket is increasing, but it's read-only.

有没有办法重置缓冲区,以便在断开连接时发送的消息不会自动发送?

Is there any way to reset the buffer so that messages sent while disconnected is not auto-sent?

推荐答案

我认为您正在寻找的方法是确保 readyState 属性 等于 1:

I think the approach you're looking for is to make sure that the readyState attribute equals 1:

if(ws.readyState == 1)
   ws.send("hi!");

这将防止在 Websocket 断开连接时进行缓冲.

This will prevent buffering while a Websocket is disconnected.

您还可以包装原始函数以强制执行此行为而无需更改其他代码:

You can also wrap the original function to enforce this behavior without changing other code:

ws._original_send_func = ws.send;
ws.send = function(data) {
   if(this.readyState == 1)
     this._original_send_func(data);
   }.bind(ws);

另请注意,这可能是浏览器特定的问题.我在 safari 上对此进行了测试,但我不知道为什么 Safari 在 Web 套接字断开连接后会缓冲数据.

Also note that this might be a browser specific issue. I tested this on safari and I have no idea why Safari buffers data after the web socket is disconnected.

注意:我知道没有 reconnect API.浏览器使用新的 Websocket 对象重新连接.

Note: There's no reconnect API that I know of. Browsers reconnect using a new Websocket object.

连接丢失后缓冲的数据不会去任何地方,因为它与特定的(现已过时的)WebSocket 对象相关联.

The buffered data isn't going anywhere after the connection was lost, since it's associated with the specific (now obsolete) WebSocket object.

整个 WebSocket 对象应该被删除(连同它的缓冲区)或由垃圾收集器收集(确保删除对对象的任何现有引用),否则数据将继续存在于内存中.

The whole WebSocket object should be deleted (alongside it's buffer) or collected by the garbage collector (make sure to remove any existing references to the object), or the data will live on in the memory.

这篇关于如何清除websocket上的缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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