TCP Port Sharing
For a long time, I thought that only one process could listen to a specific port. As a result, most of the solutions regarding Node.js applications suggested using multiple ports for the listening applications and load balancing between them. For example, using ports 8080 and 8081, and creating 2 replicas of the Node.js web apps to listen to them respectively. However, this is not the only solution, and I was surprised to learn that there is another solution at the application level called "port sharing" among forked processes. I will now provide you with the complete details:
Node.js leverages operating system features to achieve port sharing among multiple worker processes. The exact mechanisms can vary depending on the operating system, but here's a general overview of how Node.js facilitates port sharing using the cluster module:
领英推荐
In summary, Node.js doesn't directly create multiple processes listening on the same port. Instead, it utilizes the operating system's file descriptor sharing and networking features to enable multiple processes to share the same listening socket. This approach allows Node.js to take advantage of multiple CPU cores while abstracting the low-level details of port sharing for developers. The cluster module handles much of this complexity behind the scenes, making it easier to write scalable applications without worrying about the intricacies of port sharing.
If you want to create a diagram like the one in this article tell me to provide the way in the next article.