Last active
April 28, 2020 10:09
-
-
Save 1000copy/9d15209dac0945d13278ad6c01141be8 to your computer and use it in GitHub Desktop.
multicast.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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