Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear buffer on websocket?

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?

like image 697
emil Avatar asked Dec 20 '17 01:12

emil


People also ask

Are websockets buffered?

WebSocket communication consists of messages and application code and does not need to worry about buffering, parsing, and reconstructing received data. For example, if the server sends a 1 MB payload, the application's onmessage callback will be called only when the entire message is available on the client.

What causes WebSocket error?

The most common cause of Websocket error is when you connect to DSS through a proxy. Websockets is a fairly recent protocol and many enterprise proxies do not support it. The websocket connection will not establish and you will see this message.


1 Answers

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.

like image 59
Myst Avatar answered Sep 19 '22 07:09

Myst