How to clear buffer on websocket?

12,165

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.

Share:
12,165
emil
Author by

emil

Updated on June 24, 2022

Comments

  • emil
    emil almost 2 years

    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 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?