Nodejs Dgram Module
[Node.js Built-in Modules](#)
* * *
Node.js's `dgram` module provides an implementation of UDP (User Datagram Protocol) datagram sockets. UDP is a connectionless transport layer protocol. Unlike TCP, it does not guarantee reliable data transmission, but offers lower latency and higher transmission efficiency.
### Main Features
* **Connectionless**: Data can be sent without establishing a connection
* **Lightweight**: Small protocol header overhead (only 8 bytes)
* **Efficient**: No overhead for connection establishment and teardown
* **Unreliable**: Does not guarantee packet ordering or delivery
* * *
## Core API Analysis
### 1. Creating a Socket
## Example
const dgram = require('dgram');
// Create UDP socket
const socket = dgram.createSocket('udp4');// IPv4
// or
const socket = dgram.createSocket('udp6');// IPv6
#### Parameter Description
* `udp4`: Use IPv4
* `udp6`: Use IPv6
* * *
### 2. Binding to a Port
## Example
socket.bind(41234,()=>{
console.log('Socket is listening on port 41234');
});
#### Optional Parameters
* `port`: Port number to bind (random by default)
* `address`: IP address to bind (all available interfaces by default)
* `callback`: Callback function after successful binding
* * *
### 3. Sending Messages
## Example
const message = Buffer.from('Hello UDP!');
const port =41234;
const host ='127.0.0.1';
socket.send(message, port, host,(err)=>{
if(err)throw err;
console.log('Message sent');
});
#### Parameter Description
1. `msg`: Message to send (Buffer, String, or Array)
2. `offset`: Offset of message in Buffer
3. `length`: Number of bytes in message
4. `port`: Target port
5. `address`: Target address
6. `callback`: Callback after sending completes
* * *
### 4. Receiving Messages
## Example
socket.on('message',(msg, rinfo)=>{
console.log(`Received ${msg.length} bytes from ${rinfo.address}:${rinfo.port}`);
console.log(`Message content: ${msg.toString()}`);
});
#### Callback Parameters
* `msg`: Received message (Buffer)
* `rinfo`: Remote address information object
* `address`: Sender IP
* `port`: Sender port
* `family`: IP protocol family (IPv4/IPv6)
* `size`: Message size (bytes)
* * *
### 5. Closing the Socket
## Example
socket.close(()=>{
console.log('Socket closed');
});
#### Notes
* Cannot send or receive messages after closing
* Can listen for `'close'` event
* * *
## Event Handling
`dgram` sockets are EventEmitters and can listen for the following events:
### 1. 'message' Event
Triggered when a new datagram is received
### 2. 'listening' Event
Triggered when the socket starts listening
### 3. 'close' Event
Triggered when the socket is closed
### 4. 'error' Event
Triggered when an error occurs
## Example
socket.on('error',(err)=>{
console.error(`Socket error:n${err.stack}`);
socket.close();
});
* * *
## Practical Application Scenarios
### 1. Real-time Games
Utilize UDP's low latency characteristics for transmitting game state updates
### 2. Video/Audio Streaming
Scenarios that tolerate some data loss but require low latency
### 3. DNS Queries
DNS protocol typically uses UDP
### 4. Network Discovery Protocols
Such as SSDP (Simple Service Discovery Protocol)
* * *
## Complete Example
### UDP Server
## Example
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('message',(msg, rinfo)=>{
console.log(`Server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening',()=>{
const address = server.address();
console.log(`Server listening ${address.address}:${address.port}`);
});
server.bind(41234);
### UDP Client
## Example
const dgram = require('dgram');
const client = dgram.createSocket('udp4');
const message = Buffer.from('Hello UDP Server');
client.send(message,41234,'localhost',(err)=>{
if(err)throw err;
console.log('Message sent');
client.close();
});
* * *
## Notes
1. **Message Size Limit**: UDP datagram maximum is 65507 bytes (IPv4)
2. **Reliability**: Application layer needs to implement retransmission and acknowledgment mechanisms
3. **Security**: UDP is vulnerable to IP spoofing and DDoS attacks
4. **Firewall**: Ensure firewall allows UDP traffic
* * *
## Performance Optimization Suggestions
1. Reuse socket address (SO_REUSEADDR)
2. Appropriately adjust receive buffer size
3. Batch process messages to reduce system calls
4. Consider using setRecvBufferSize() and setSendBufferSize()
* * *
## Summary
Node.js's `dgram` module provides developers with powerful UDP network programming capabilities, especially suitable for network application scenarios requiring low latency and high efficiency. Although UDP does not provide reliability guarantees, this trade-off is acceptable in many real-time applications. Understanding UDP's characteristics and the `dgram` module's API can help developers build more efficient network applications.
[Node.js Built-in Modules](#)
YouTip