Skip to content

Instantly share code, notes, and snippets.

@andris9
Last active June 21, 2021 12:55
Show Gist options
  • Save andris9/6536380 to your computer and use it in GitHub Desktop.
Save andris9/6536380 to your computer and use it in GitHub Desktop.
udp broadcats client
var dgram = require("dgram");
var port = 18432,
multicastIP = "224.3.56.114";
var client = dgram.createSocket('udp4');
client.bind(port, "0.0.0.0");
client.on("listening", function(){
client.setBroadcast(true);
client.setMulticastTTL(128);
client.setMulticastLoopback(true);
client.addMembership(multicastIP, "0.0.0.0");
});
client.on("message", function(message){
console.log("MUTLICAST MESSAGE");
console.log(message.toString());
});
var dgram = require('dgram');
var message = new Buffer(Date());
var sender = dgram.createSocket("udp4");
var port = 18432,
multicastIP = "224.3.56.114";
sender.bind();
sender.on("listening", function(){
sender.setBroadcast(true);
sender.setMulticastTTL(128);
sender.setMulticastLoopback(true);
sender.addMembership(multicastIP, "0.0.0.0");
sender.send(message, 0, message.length, port, multicastIP, function(err, bytes) {
sender.close();
});
});
@Miliks
Copy link

Miliks commented Jun 21, 2021

if there is no udp server running how can I verify it before sending the message?

@andris9
Copy link
Author

andris9 commented Jun 21, 2021

You can’t, UDP is one way protocol - you send the packet and hope for the best. One option would be to design your own protocol over UDP where both ends exchange confirmation packets or something like that.

@Miliks
Copy link

Miliks commented Jun 21, 2021

but if there is no end-point listening udp client doesn't care? no chance to verify even knowing specific host and port? unfortunately, I'm managing only the client part, and the server is not sending anything before I send the first message to it. Do u think it could be possible to use any TCP library?

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