node.js - Sending UDP messages from multiple worker processes -
in node.js i'm having problems using dgram child processes. if try send udp messages multiple worker processes, messages 1 of processes sent.
if run code below , run netcat listen on udp (nc -ul 8111
), should see 1 of workers sending udp messages, though there multiple workers logging 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 " + workerid + "\n"); socket.send(message, 0, message.length, 8111, 'localhost'); }, 1000); } if (cluster.ismaster) { (var = 0; < numcpus; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); }); } else { dosocketstuff(); }
i have seen issue on osx node.js 5.1.0 , on windows node.js 4.2.6.
this behavior comes netcat
. quoting this answer:
when nc listening udp socket, 'locks on' source port , source ip of first packet receives.
if listen messages differently, should see them all. example:
require('dgram').createsocket('udp4') .bind(8111) .on('message', function (buf) { console.log(buf.tostring()); });
Comments
Post a Comment