The WebSocket bufferedAmount attribute


If you have been working or planning to work with HTML5 WebSocket you may end up transporting large amounts of data and/or you may have the requirement to transport data as fast as possible. 

The WebSocket object has an attribute called bufferedAmount that's particularly useful to check for the amount of data buffered for transmission to the server. You can use the bufferedAmount attribute to check the number of bytes that have been queued but not yet transmitted to the server.

The values reported in that attribute don’t include framing overhead incurred by the protocol or buffering done by the operating system or network hardware.

The code below shows an example of how to use the bufferedAmount attribute to keep sending updates every second, if the network can handle that rate, or at whatever rate the network can handle, if that is too fast.

// Buffering threshold at 10k
var THRESHOLD = 10240;

// Create a New WebSocket connection
var mySocket = new WebSocket(“ws://echo.websocket.org/updates”);

// Listen for the opening event
mySocket.onopen = function () {
 setInterval(function() {

// Check for amount of data buffered but not sent yet //and then send an update in case there is nothing //in the buffer
if (mySocket.bufferedAmount < THRESHOLD)
                                    mySocket.send(getUpdateData());
                  }, 1000);
};

Using the bufferedAmount attribute can be useful for throttling the rate at the applications send data to the server avoiding network saturation.

Popular posts from this blog

How to Declare Variables in MS-SQL Server Management Studio

Calling Web Services with Apache Camel

Using HTTP-based endpoints with Apache Camel