In Node.js I'm having problems using dgram from child processes. If I try to send UDP messages from multiple worker processes, only messages from one of the processes actually get sent.
If you run the code below and also run something like Netcat to listen on UDP (nc -ul 8111
), you should see that only one of the workers is successfully sending UDP messages, even though there are multiple workers logging to the console.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
const dgram = require('dgram');
function doSocketStuff() {
var socket = dgram.createSocket('udp4');
var workerId = cluster.isMaster ? 'master' : cluster.worker.id;
setInterval(() => {
console.log("Worker " + workerId);
var message = new Buffer("UDP from " + workerId + "\n");
socket.send(message, 0, message.length, 8111, 'localhost');
}, 1000);
}
if (cluster.isMaster) {
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
doSocketStuff();
}
I have seen this issue on OSX with Node.js 5.1.0 and on Windows with Node.js 4.2.6.