How to clear buffer on websocket?

后端 未结 1 1930
[愿得一人]
[愿得一人] 2021-01-18 08:50

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

I can see that bufferedAmount of websock

相关标签:
1条回答
  • 2021-01-18 09:42

    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!");
    

    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);
    

    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.

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

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

    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.

    0 讨论(0)
提交回复
热议问题