Node.js dgram Module in Detail
Node.js's dgram The 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 delivery, but offers lower latency and higher transmission efficiency.
Main Features
- Connectionless: No connection needs to be established before sending data
- Lightweight: Low protocol header overhead (only 8 bytes)
- High efficiency: No overhead for connection establishment and teardown
- Unreliable: Does not guarantee the order and arrival of packets
Core API Analysis
1. Creating a Socket
Example
const
dgram
=
require
(
'dgram'
)
;
// Create a UDP socket
const
socket
=
dgram.
createSocket
(
'udp4'
)
;
// IPv4
// or
const
socket
=
dgram.
createSocket
(
'udp6'
)
;
// IPv6
Parameter Description
udp4: Use IPv4udp6: Use IPv6
2. Binding a Port
Example
socket.
bind
(
41234
,
(
)
=>
{
console.
log
(
'Socket is listening on port 41234'
)
;
}
)
;
Optional arguments
port: The port number to bind (random by default)address: The IP address to bind (all available interfaces by default)callback: The callback function invoked after a successful bind
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
msg: The message to send (Buffer, String, or Array)offset: The offset of the message within the Bufferlength: The number of bytes in the messageport: The destination portaddress: The destination addresscallback: The callback invoked 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: The received message (Buffer)rinfo: The remote address information objectaddress: Sender IPport: Sender portfamily: IP address family (IPv4/IPv6)size: Message size (in bytes)
5. Closing a Socket
Example
socket.
close
(
(
)
=>
{
console.
log
(
'Socket closed'
)
;
}
)
;
Notes
- Once closed, the socket can no longer send or receive messages
- Can Listen For
'close'Events
Event Handling
dgram A socket is an EventEmitter and can listen for the following events:
1. The 'message' Event
Emitted when a new datagram is received
2. The 'listening' Event
Emitted when the socket starts listening
3. The 'close' Event
Emitted when the socket is closed
4. The 'error' Event
Emitted 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
Leveraging UDP's low-latency characteristics to transmit game state updates
2. Video/Audio Streaming
Scenarios that tolerate a small amount of data loss but require low latency
3. DNS Queries
The 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
- Message Size Limit: A UDP datagram is at most 65507 bytes (IPv4)
- Reliability: The application layer needs to implement retransmission and acknowledgment mechanisms
- Safety: UDP is vulnerable to IP spoofing and DDoS attacks
- Firewall: Ensure the firewall allows UDP traffic
Performance Optimization Suggestions
- Reuse socket addresses (SO_REUSEADDR)
- Adjust the receive buffer size appropriately
- Process messages in batches to reduce system calls
- Consider using setRecvBufferSize() and setSendBufferSize()
Summary
Node.js's dgram The module provides developers with powerful UDP network programming capabilities, especially suited for network application scenarios that require 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