Module basic module

Module dgram

dgram is one of the basic modules, mainly used to implement UDP data packet socket encapsulation.

Steps for usage:

  1. First, introduce the dgram module through the following statement.

    1
    var dgram = require('dgram');
  2. Create a UDP packet socket instance.

    1
    var sock = dgram.createSocket('udp4');
  3. Register the data reception event message callback function for the UDP packet socket.

    1 2 3
    sock.on('message', function (msg, rinfo) { // process received message });
  4. Sends a UDP packet message to the specified destination address.

    1 2 3 4 5
    var msg = ...; // message to send var port = ...; // destination port var host = ...; // destination host var bytes = sock.send(msg, 0, msg.length, port, host); console.log('UDP message sent to ' + host + ':' + port);

object

Socket

dgram.SocketThe object is a package function that encapsulates the functionEventEmitter. SeeDgramSocket

1
DgramSocket dgram.Socket;

dgram.SocketInstance is given bydgram.createSocket() created. createdgram.SocketInstances do not need to use the new keyword.

static function

createSocket

Createdgram.Socketobject

1
static DgramSocket dgram.createSocket(Object opts);

Call parameters:

  • opts: Object,

Return results:

Options allowed by opts are:

1 2 3 4 5 6 7
{ "type": "udp4" | "udp6", // socket type "reuseAddr": true | false, // reuse address, default is false "ipv6Only": true | false, // only accept IPv6 packets, default is false "recvBufferSize": 1024, // specify the size of the receive buffer "sendBufferSize": 1024 // specify the size of the send buffer }

Createdgram.Socketobject

1 2
static DgramSocket dgram.createSocket(Object opts, Function callback);

Call parameters:

  • opts: Object,
  • callback: Function, adds a listener for the 'message' event.

Return results:

Options allowed by opts are:

1 2 3 4 5 6 7
{ "type": "udp4" | "udp6", // socket type "reuseAddr": true | false, // reuse address, default is false "ipv6Only": true | false, // only accept IPv6 packets, default is false "recvBufferSize": 1024, // specify the size of the receive buffer "sendBufferSize": 1024 // specify the size of the send buffer }

Createdgram.Socketobject

1
static DgramSocket dgram.createSocket(String type);

Call parameters:

  • type: String, socket family, 'udp4' or 'udp6'.

Return results:


Createdgram.Socketobject

1 2
static DgramSocket dgram.createSocket(String type, Function callback);

Call parameters:

  • type: String, socket family, 'udp4' or 'udp6'.
  • callback: Function, adds a listener for the 'message' event.

Return results: