NODEJS's socket broadcast

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.