Using Node.JS and cluster
module.
I am trying to understand how multiple forked child processes can listen on the same port.
For example, using cluster
module we can do this:
const port = 443;
...
if (cluster.isMaster) {
for(let i = 0; i < numCPUs; i++)
{
cluster.fork();
}
...
}
else // Forked child processes:
{
...
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
}, app)
.listen(port, () => {
console.log(`HTTPS Listening on port ${port}`);
});
}
This code forks multiple processes, all of which call listen
on the same port. I'm not clear on how all the processes could bind the same port and still be able to determine which process gets the port traffic. Is this actually an illusion, and instead the master process is actually the only one binding the port and passing the requests randomly to the forked children? (If this is the case, isn't there a performance hit?)
Thanks for helping me understand how all the child processes can listen on same port at same time.
NOTE that this example is running on a Windows machine, but if I understand correctly, it is compatible with both Windows and Linux.