Nodejs implements a simple udp Broadcast Server, client _ node. js

Source: Internet
Author: User
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.

Related Article

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.