nodejs發送udp廣播還蠻簡單的,我們先寫個伺服器用於接收廣播數據,程式碼如下:
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 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了。