Reputation: 1163
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.
Upvotes: 0
Views: 649
Reputation: 4711
This behavior likely comes from netcat
. Quoting from this answer:
When nc is listening to a UDP socket, it 'locks on' to the source port and source IP of the first packet it receives.
If you listen to your messages differently, you should see them all. For example:
require('dgram').createSocket('udp4')
.bind(8111)
.on('message', function (buf) { console.log(buf.toString()); });
Upvotes: 1