r03 r03 - 1 year ago 303
Node.js Question

Node.js flush socket after write

I'm implementing a tcp protocol in Node.

Full source:




The problem is that I use this to send a package:


If I send multiple commands, then multiple commands are combined into a single tcp packet.

This doesn't work.

There are more questions about this on SO, but they recommend using a delimeter.

But since I can't change the protocol this isn't an option.

Isn't there a simple solution to flush the socket?

socket.setNoDelay() doesn't help.

Edit: I also tried to use the drain event to send the next write, but the event is never called?


This seems to solve the problem, but is very uggly and I don't now if it always works.

Instead of writing it directly I write to a buffer:


Every cycle(?) I'm writing a package to the socket stream:

var sendCycle = function(ads) {
if (ads.writeFILO.length > 0) {
setTimeout(function() {
}, 0);


I refer to the socket.write(data, [encoding], [callback]) API:

The optional callback parameter will be executed when the data is finally written out - this may not be immediately.

So, set up a queue (array is fine) which holds messages to be sent.
When the above callback is being called, check the queue and send if needed..

This however does not guarantee what you're looking for, you'll have to test. Unfortunately the docs don't explicitly state when there's an acknowledgement from the remote end point that it actually received that message...

In the end, as you concluded, TCP is a stream.

An interesting idea which just came up to me now, however, if you're FORCED TO use an existing protocol, then open two TCP connections.
When one connection acknowledges (whatever the higher-level protocol is) receiving that message, send the next through the other one... and so forth..

Anyway, nice challenge :)