Skip to content

Instantly share code, notes, and snippets.

@mdodsworth
Created August 27, 2012 16:23
Show Gist options
  • Save mdodsworth/3490042 to your computer and use it in GitHub Desktop.
Save mdodsworth/3490042 to your computer and use it in GitHub Desktop.
node: multicast example
var dgram = require('dgram');
var socket = dgram.createSocket('udp4');
var testMessage = "[hello world] pid: " + process.pid;
var multicastAddress = '239.1.2.3';
var multicastPort = 5554;
socket.bind(multicastPort, '0.0.0.0');
socket.addMembership(multicastAddress);
socket.on("message", function ( data, rinfo ) {
console.log("Message received from ", rinfo.address, " : ", data.toString());
});
setInterval(function () {
socket.send(new Buffer(testMessage),
0,
testMessage.length,
multicastPort,
multicastAddress,
function (err) {
if (err) console.log(err);
console.log("Message sent");
}
);
}, 1000);
@draeder
Copy link

draeder commented Sep 6, 2022

Working:

import dgram from 'node:dgram'
const address = '239.1.2.3'
const port = 5554

let socket = dgram.createSocket({
  type: 'udp4',
  reuseAddr: true // for testing multiple instances on localhost
})

socket.bind(port)

socket.on('message', (msg, remote) => {
  console.log(msg.toString().trim())
})

socket.on("listening", function() {
  this.setBroadcast(true)
  this.setMulticastTTL(128)
  this.addMembership(address)
  console.log('Multicast listening . . . ')
})

setInterval(()=>{
  let message = 'Hi! ' + new Date().getTime()
  socket.send(message, 0, message.length, port, address)
}, 500)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment