nodejs發送udp廣播還是蠻簡單的,我們先寫個服務器用於接收廣播數據,代碼如下:
代碼如下:
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);
然後寫個客戶端程序,發送廣播消息,代碼如下:
代碼如下:
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();
});
這裡需要注意的是socket.setBroadcast(true);必須在綁定socket成功後才能調用,否則會報Error: setBroadcast EBADF的錯誤。
客戶端發送廣播還是蠻簡單的,設置好需要發送的數據和端口等信息就OK了。