When writing a nodejs proxy server I noticed that data may come into my proxy many times before the data is written to the other socket end. each time my data comes in, i call socket.write(); …
However I am unsure if the order of the data being transmitted is guaranteed by nodejs to be the same as the order i scheduled the writes due to the asynchronous nature of the sending.
Does anyone know the behavior of nodejs in this situation?
If the order is not guaranteed, then i will have to buffer the data until i recieve the data successfully sent callback.
Problem courtesy of: Andrew Chambers
Node.jsis single threaded and can only ever do one thing at a time. It has a queue of callbacks that get processed in order.
some more information can be found here: http://howtonode.org/understanding-process-next-tick
As long as you are calling socket.write when you receive data then it will arrive in order. If you think about it, if it didn’t do this then node would not be usable as a webserver. For example, a simple node express site might use fs.readfile to read a file from disc asynchronously and serve it back to the browser using socket.write. If the order was not guaranteed, that file might not be returned correctly.
From the node 0.8.14 documentation: http://nodemanual.org/latest/nodejs_ref_guide/net.html#net.Socket.write
Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' is emitted when the buffer is again free.
net.Socket has the property that socket.write() always works. This is
to help users get up and running quickly. The computer can’t always
keep up with the amount of data that is written to a socket—the
network connection simply might be too slow. Node.js
queue up the data written to a socket and send it out over the wire
whenever it’s possible. (Internally, it’s polling on the socket’s file
descriptor for being writable.)
Solution courtesy of: AndyD