It is quite simple to send udp broadcasts from nodejs. Let’s write a server to receive broadcast data first. The code is as follows:
The code copy is as follows:
var dgram = require("dgram");
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 and send a broadcast message, the code is as follows:
The code copy is as follows:
var dgram = require("dgram");
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();
});
What you need to note here is socket.setBroadcast(true); it must be called after the socket is bound successfully, otherwise an error: setBroadcast EBADF will be reported.
It is quite simple for the client to send broadcasts. It is OK to set up the data and ports that need to be sent.