This article mainly introduces a simple udp broadcast server and client implemented by Nodejs. This article provides the implementation code directly. If you need it, you can refer to nodejs to send udp broadcast, write a server to receive broadcast data. The Code is as follows:
The Code 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. Binary (41234 );
Then write a client program to send a broadcast message. The Code is as follows:
The Code 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, '2017. limit 255', function (err, bytes ){
Socket. close ();
});
Note that socket. setBroadcast (true); can be called only after the socket is successfully bound; otherwise, an Error: setBroadcast EBADF is reported.
It is quite simple for the client to send a broadcast. It is okay to set the data to be sent, the port, and other information.