Skip to content

Instantly share code, notes, and snippets.

@supershabam
Created June 13, 2012 16:48
Show Gist options
  • Save supershabam/2925218 to your computer and use it in GitHub Desktop.
Save supershabam/2925218 to your computer and use it in GitHub Desktop.
Demonstrates bug in NodeJS 'net' module under clustering
/**
* This demonstrates how server.listen with port set to zero
* does not function properly in a cluster environment.
*
* EXPECTED RESULT: each worker's server starts listening on a
* unique port as per documentation "A port value of zero will assign a random port."
*
* ACTUAL DEMONSTRATED RESULT: each worker's server starts listening
* on the exact same port as every other worker.
*/
"use strict";
var cluster = require('cluster')
, net = require('net')
, numForks = 5
, i
;
if (cluster.isMaster) {
// fork workers
for (i = 0; i < numForks; ++i) {
cluster.fork();
}
} else {
// worker code - create variable scope with executed function
(function() {
var server = net.createServer();
/**
* server.listen(port, [host], [listeningListener])
* Begin accepting connections on the specified port and host. If the host
* is omitted, the server will accept connections directed to any IPv4 address
* (INADDR_ANY). A port value of zero will assign a random port.
*/
server.listen(0);
server.on('listening', function() {
var address = server.address()
, port = address.port
;
console.log(port);
});
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment