Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 16:35:38
Original
2305 people have browsed it

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template