[Libwebsockets] browser flow-control

Per Bothner per at bothner.com
Sun Mar 12 16:15:33 CET 2017

I have a WebSockets problem that isn't specifically libwebsockets,
but perhaps someone has a recommendation.  The problem (which appears to be well-known)
is that there isn't any way to limit the rate that JavaScript gets "onmeessage"
calls when receiving data from a server.  I run into this with ldomterm
when I have a child process that spews data in an infinite loop.  The network
bandwidth does not slow things down, so in the browser the WebSocket.onmeessage
just gets call repreatedly,and the browser can't keep up.  Worse,
the onmessage calls prevent any other JavaScript events from being acted on,
so I can't (for example) send a ctrl-c.  The only solution is to kill
either the browser or the server.

Conceptually, the solution is simple: The browser has to send a "I'm ready
for more" message to the server when it is ready, and the server must stop
sending date until it gets this message.  But the devil is in the details.

The best I can think of: Both the server and the browser maintain a count
of number bytes (or characters) respectively sent and received.  The browser has:
After processing a message of N bytes, the browser does:
   bytesProcessed += N;
   if (bytesProcessed > bytesReported + 500) {
       bytesReported = bytesProcessed;
The server:
receive_ready_for_more_message(N) {
   bytesReported = N;
   if (client_suspended) wake_up_client();
send_message(msg) {
   bytesSent += msg.length;
   if (bytesSent > bytesReported + 2000)

Suspending can mean no longer reading from the client (in which case
it will suspend when its buffer is full).  One could also use job-control signals.

Does this make sense?  Can you think of anything better?  To avoid counter overflow
one could either divide all the counters (by say 100), and/or handle wrap-around (all
counters are modulo 1<<20).

I've implemented a builtin 'less'-like pager for ldomterm, and the plan is to integrate
this into the flow-control: In auto-pager mode, automatic scroll suspends display update
and enters paging mode, until the users scrolls forward to enable more output.
	--Per Bothner
per at bothner.com   http://per.bothner.com/

More information about the Libwebsockets mailing list