数据报处理(UDP/Datagram)

稳定度:2 - 稳定

dgram 模块提供了对 UDP 数据报套接字的实现。

  1. const dgram = require('dgram');
  2. const server = dgram.createSocket('udp4');
  3. server.on('error', (err) => {
  4. console.log(`server error:\n${err.stack}`);
  5. server.close();
  6. });
  7. server.on('message', (msg, rinfo) => {
  8. console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
  9. });
  10. server.on('listening', () => {
  11. var address = server.address();
  12. console.log(`server listening ${address.address}:${address.port}`);
  13. });
  14. server.bind(41234);
  15. // server listening 0.0.0.0:41234