Skip to content

Instantly share code, notes, and snippets.

@1000copy
Created April 28, 2020 10:08
Show Gist options
  • Save 1000copy/f320bdb2967db388440a2f915457be93 to your computer and use it in GitHub Desktop.
Save 1000copy/f320bdb2967db388440a2f915457be93 to your computer and use it in GitHub Desktop.
multicast.js
const PORT = 20000;
const MULTICAST_ADDR = "233.255.255.255";
/*Here, choose the port that we will bind the socket to and the multicast address we will use. The multicast group address must be within the appropriate multicast address space. Much of the space is reserved, but you can still find some unassigned ad-hoc space such as 233.252.18.0-233.255.255.255.*/
const dgram = require("dgram");
const process = require("process");
const socket = dgram.createSocket({ type: "udp4", reuseAddr: true });
socket.bind(PORT);
socket.on("listening", function() {
socket.addMembership(MULTICAST_ADDR);
setInterval(sendMessage, 2500);
const address = socket.address();
console.log(
`UDP socket listening on ${address.address}:${address.port} pid: ${
process.pid
}`
);
});
function sendMessage() {
const message = Buffer.from(`Message from process ${process.pid}`);
socket.send(message, 0, message.length, PORT, MULTICAST_ADDR, function() {
console.info(`Sending message "${message}"`);
});
}
socket.on("message", function(message, rinfo) {
console.info(`Message from: ${rinfo.address}:${rinfo.port} - ${message}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment