I am trying to use node:dgram
to multicast bidirectionally on a single machine using two instances.
-----------PC-----------
send message / ........../\.......... \ receive message
receive message \ ........./..\......... / send message
--Instance1..Instance2--
Both Instance1 and Instance2 should receive their own and each others' messages.
I plan to deduplicate messages later, but this is a basic diagram of what I'm trying to achieve.
What is happening with the following code is Instance1 receives its own messages fine. However, when Instance2 starts, Instance1 receives its own messages plus messages from Instance2, but Instance2 never receives messages from Instance1, nor its own messages
import dgram from 'node:dgram'
let PORT = 30210
let MCAST_ADDR = "230.185.192.108"
let server = dgram.createSocket("udp4")
server.bind(PORT, function(err){
if(err) console.log(err)
server.setBroadcast(true)
server.setMulticastTTL(128)
server.addMembership(MCAST_ADDR)
})
setInterval(broadcastNew, 3000)
server.on('message', function (message, remote) {
console.log('MCast Msg: From: ' + remote.address + ':' + remote.port +' - ' + message)
})
function broadcastNew() {
let msg = [
Math.random().toString()
]
let message = Buffer.from(msg[Math.floor(Math.random()*msg.length)])
server.send(message, 0, message.length, PORT, MCAST_ADDR)
console.log("Sent " + message + " to the wire...")
}
How can I solve this?