Module dgram
dgram is one of the basic modules, mainly used to implement UDP data packet socket encapsulation.
Steps for usage:
First, introduce the dgram module through the following statement.
1var dgram = require('dgram');Create a UDP packet socket instance.
1var sock = dgram.createSocket('udp4');Register the data reception event message callback function for the UDP packet socket.
1 2 3sock.on('message', function (msg, rinfo) { // process received message });Sends a UDP packet message to the specified destination address.
1 2 3 4 5var 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
1DgramSocket dgram.Socket;
dgram.SocketInstance is given bydgram.createSocket() created. createdgram.SocketInstances do not need to use the new keyword.
static function
createSocket
Createdgram.Socketobject
1static DgramSocket dgram.createSocket(Object opts);
Call parameters:
- opts: Object,
Return results:
- DgramSocket, returns the createdSocketobject
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
2static DgramSocket dgram.createSocket(Object opts,
Function callback);
Call parameters:
- opts: Object,
- callback: Function, adds a listener for the 'message' event.
Return results:
- DgramSocket, returns the createdSocketobject
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
1static DgramSocket dgram.createSocket(String type);
Call parameters:
- type: String, socket family, 'udp4' or 'udp6'.
Return results:
- DgramSocket, returns the createdSocketobject
Createdgram.Socketobject
1
2static 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:
- DgramSocket, returns the createdSocketobject