模块概览

dgram模块是对UDP socket的一层封装,相对net模块简单很多,下面看例子。

UPD客户端 vs UDP服务端

首先,启动UDP server,监听来自端口33333的请求。

server.js

  1. // 例子:UDP服务端
  2. var PORT = 33333;
  3. var HOST = '127.0.0.1';
  4. var dgram = require('dgram');
  5. var server = dgram.createSocket('udp4');
  6. server.on('listening', function () {
  7. var address = server.address();
  8. console.log('UDP Server listening on ' + address.address + ":" + address.port);
  9. });
  10. server.on('message', function (message, remote) {
  11. console.log(remote.address + ':' + remote.port +' - ' + message);
  12. });
  13. server.bind(PORT, HOST);

然后,创建UDP socket,向端口33333发送请求。

client.js

  1. // 例子:UDP客户端
  2. var PORT = 33333;
  3. var HOST = '127.0.0.1';
  4. var dgram = require('dgram');
  5. var message = Buffer.from('My KungFu is Good!');
  6. var client = dgram.createSocket('udp4');
  7. client.send(message, PORT, HOST, function(err, bytes) {
  8. if (err) throw err;
  9. console.log('UDP message sent to ' + HOST +':'+ PORT);
  10. client.close();
  11. });

运行 server.js。

  1. node server.js

运行 client.js。

  1. 2016.12.22-dgram git:(master) node client.js
  2. UDP message sent to 127.0.0.1:33333

服务端打印日志如下

  1. UDP Server listening on 127.0.0.1:33333
  2. 127.0.0.1:58940 - My KungFu is Good!

广播

通过dgram实现广播功能很简单,服务端代码如下。

  1. var dgram = require('dgram');
  2. var server = dgram.createSocket('udp4');
  3. var port = 33333;
  4. server.on('message', function(message, rinfo){
  5. console.log('server got message from: ' + rinfo.address + ':' + rinfo.port);
  6. });
  7. server.bind(port);

接着创建客户端,向地址’255.255.255.255:33333’进行广播。

  1. var dgram = require('dgram');
  2. var client = dgram.createSocket('udp4');
  3. var msg = Buffer.from('hello world');
  4. var port = 33333;
  5. var host = '255.255.255.255';
  6. client.bind(function(){
  7. client.setBroadcast(true);
  8. client.send(msg, port, host, function(err){
  9. if(err) throw err;
  10. console.log('msg has been sent');
  11. client.close();
  12. });
  13. });

运行程序,最终服务端打印日志如下

  1. 2016.12.22-dgram git:(master) node broadcast-server.js
  2. server got message from: 192.168.0.102:61010

相关链接

https://nodejs.org/api/dgram.html