首页 > 代码库 > Nodejs之socket广播

Nodejs之socket广播

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了。