Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io emit() delay / buffer flush?

I'm using socket.io to send messages to browser. On node.js side I'm doing

socket.emit('message', data);

On browser-side I'm doing

socket.on('message', handleData);

Now this works fine. For testing purposes I'm manually triggering (from node-inspector console) the socket.emit(). I'm able to do this 2-3 times after which the next message takes a long time to deliver. About 10 seconds.

My messages are rather short. Compression is enabled and the object JSON {"could be about": "this long"}. When testing with longer strings, all messages are sent instantly. So this has something to do with buffering/optimization, but in our case, it's important that all messages are sent instantly.

Does anyone have any insight into this delay? Thanks

like image 673
Olav Kokovkin Avatar asked Jan 20 '26 11:01

Olav Kokovkin


2 Answers

A link to the official documentation (v4.0):

https://socket.io/docs/v4/client-offline-behavior/

Indeed there are three ways to fight buffering on client side:

  • use the connected attribute of the Socket instance
if (socket.connected) {
  socket.emit( /* ... */ );
} else {
  // ...
}
  • use volatile events
socket.volatile.emit( /* ... */ );
  • empty the internal buffer upon reconnection
socket.on("connect", () => {
  socket.sendBuffer = [];
});

Docs on volatile emits:

https://socket.io/docs/v4/emitting-events/#Volatile-events

like image 131
shitpoet Avatar answered Jan 21 '26 23:01

shitpoet


I had the same problem. Although it's been years, these tips would be useful to someone else witht eh problem.

  1. How To Cancel, Timeout, or Clear Queued Messages In Socket.IO

  2. https://github.com/feathersjs/feathers/issues/1532

    socket.on('connect', function() { socket.sendBuffer = []; // do stuff });

    socket.on('reconnect', function() { socket.sendBuffer = []; });

like image 42
sandeepani Avatar answered Jan 21 '26 23:01

sandeepani