Sending UDP broadcasts in nodejs is quite simple. Let’s first write a server to receive broadcast data. The code is as follows:
var server = dgram.createSocket("udp4");
server.on("error", function (err) {
console.log("server error:n" err.stack);
server.close();
});
server.on("message", function (msg, rinfo) {
console.log("server got: " msg " from "
rinfo.address ":" rinfo.port);
});
server.on("listening", function () {
var address = server.address();
console.log("server listening "
address.address ":" address.port);
});
server.bind(41234);
Then write a client program to send broadcast messages. The code is as follows:
var socket = dgram.createSocket("udp4");
socket.bind(function () {
socket.setBroadcast(true);
});
var message = new Buffer("Hi");
socket.send(message, 0, message.length, 41234, '255.255.255.255', function(err, bytes) {
socket.close();
});
It should be noted here that socket.setBroadcast(true); must be called after the socket is successfully bound, otherwise an Error: setBroadcast EBADF error will be reported.
Sending broadcasts from the client is quite simple. Just set the data and port to be sent and it’s OK.