简体   繁体   中英

In Node.js, is writing to a TCP connection blocking?

I have a node.js process which has several entry points, including a tcp server, websocket server, and named pipe server. I am wondering if any interactions with these connections will be blocking.

Example: for a given connection, if there isnt anything in the buffer because the client didnt send anything yet, will this block all other code from running in the Node.js process until the client sends data?

My understanding is that node will offload I/O operations like these to the system kernel, so it wouldnt hold up the call stack.

Most likely I am getting something wrong here so please let me know. Thank you.

This is a very interesting question!

I would recommend you to start by understanding what the event loop is (reading https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ ) and then understanding the difference between blocking & non-blocking calls (reading https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/ ).

Now we'll know a bit more about how node works behind the scenes, what blocking and non-blocking operations are and therefore we're equipped to understand and spot what will or won't block our loop.

Will a TCP connection block it? There may be a module out there that will, it really depends on each case, library, implementation.

Regarding TCP on the "native" implementation, if you're using the node.js Net module you'll find that it is a:

module [that] provides an asynchronous.network API for creating stream-based TCP or IPC servers

Therefore, in principle, it will be non-blocking.

As an example, if we look at the socket.write documentation itself, we'll find that this function:

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' will be emitted when the buffer is again free.

Therefore it should not block.

PS: Another interesting article on this subject is https://medium.com/@hnasr/when-nodejs-io-blocks-327f8a36fbd4

Happy reading, and keep an eye out for blocking function calls!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM