Nodejs send UDP broadcast is quite simple, we first write a server to receive broadcast data, the code is as follows:
varDgram = require ("Dgram");varServer = 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 () { varAddress =server.address (); Console.log ("Server Listening" +address.address+ ":" +address.port);}); Server.bind (41234);
Then write a client program, send a broadcast message, the code is as follows:
var dgram = require ("Dgram"); var socket = Dgram.createsocket ("UDP4"); Socket.bind (function () { Socket.setbroadcast (true);}); var New Buffer ("Hi"function(err, bytes) { socket.close ();});
It is important to note that Socket.setbroadcast (true) must not be called until the socket is successfully bound, otherwise it will be reported error:setbroadcast EBADF error.
It is quite simple for the client to send the broadcast, and it is OK to set up the data and ports that need to be sent.