Home  >  Article  >  Web Front-end  >  A simple udp broadcast server and client implemented by Nodejs_node.js

A simple udp broadcast server and client implemented by Nodejs_node.js

WBOY
WBOYOriginal
2016-05-16 16:35:382264browse

Sending UDP broadcasts in nodejs is quite simple. Let’s first write a server to receive broadcast data. The code is as follows:

Copy code 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.bind(41234);

Then write a client program to send broadcast messages. The code is as follows:

Copy code 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, '255.255.255.255', function(err, bytes) {
socket.close();
});

It should be noted here that socket.setBroadcast(true); must be called after the socket is successfully bound, otherwise an Error: setBroadcast EBADF error will be reported.

Sending broadcasts from the client is quite simple. Just set the data and port to be sent and it’s OK.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn