The dgram module provides UDP datagram sockets for connectionless networking. Here's how to use it.
Basic UDP Server#
Basic UDP Client#
UDP Echo Server#
IPv6 Support#
Multicast#
Broadcast#
Socket Options#
Message Framing#
Service Discovery#
UDP with Promises#
Error Handling#
Best Practices#
Socket Configuration:
✓ Use reuseAddr for multiple listeners
✓ Set appropriate buffer sizes
✓ Handle all error events
✓ Clean up on close
Message Handling:
✓ Validate incoming data
✓ Implement timeouts
✓ Handle partial messages
✓ Use sequence numbers
Multicast:
✓ Join/leave groups properly
✓ Set appropriate TTL
✓ Handle loopback
✓ Use reuseAddr
Avoid:
✗ Ignoring errors
✗ Assuming delivery
✗ Large datagrams (>512 bytes safe)
✗ Blocking operations
Conclusion#
The Node.js dgram module provides UDP networking for connectionless communication. Use it for real-time applications, service discovery, broadcasts, and multicast scenarios where occasional packet loss is acceptable. Always handle errors, implement timeouts for request-response patterns, and keep messages small for reliable delivery. For guaranteed delivery or streaming data, consider TCP with the net module instead.