UDP Programming
Welcome to UDP efficient communication practice
Why does the video call freeze for a few seconds and then jump directly? Why can DNS resolution achieve millisecond response? Why doesn’t your LAN gaming team have to wait for the handshake prompt? Today we will dismantle the "lightweight player" behind it - UDP protocol. From basic API to modern best practices, we will use Python to take you into practice.
1. Understand UDP first: it’s not “unreliable”, it’s “choose as needed”
UDP (User Datagram Protocol) is a connectionless protocol of the transport layer. Compared with the TCP we are more familiar with, it leaves all the complex reliability, sequence, and flow control mechanisms to the application layer to decide whether to add them - in exchange for ultimate lightness and speed.
One-sentence summary of core features
- No connection: Instead of shaking hands three times and waving four times, just insert the address before sending the message, just like a courier knocking on the door and inserting a package (it doesn’t matter whether you are at home or not, and whether you are willing to accept it or not);
- Unreliable and not sorted: There is no guarantee that the package will be delivered, the order is not guaranteed, and it does not even tell you that it is lost/disordered;
- Extremely lightweight: The header is only 8 bytes (the TCP header is at least 20 bytes and at most 60 bytes);
- Support broadcast/multicast: Can send "bulk broadcast" to all devices in the same LAN/specified group.
When should I use UDP?
✅ Real-time priority, high packet loss error: Video streaming, voice calls, live barrages (losing 1 frame/barrage does not affect the overall experience); ✅ Query small data: DNS, DHCP (a few KB per interaction, just resend after timeout, using TCP is a waste of time); ✅ LAN/Multicast scenario: Device discovery, game team notification.
2. Introduction to Python UDP: Write a small sending and receiving program in 10 minutes
PythonsocketThe library natively supports UDP and does not require additional installation dependencies. Let's first write the most basic "one send and one receive" version of the server and client.
Basic version server
Bind the local IP and port, receive data in an infinite loop, and return the response in the same way after receiving it (note the use ofrecvfrom()Getting the data + client address at the same time is the core of UDP programming! ).
Basic version client
There is no need to bind an address, just send a message directly to the specified server and wait for the response.
3. Modern UDP best practices: Don’t just write the entry version!
The entry version only runs through the process. The real production/development environment needs to solve problems such as timeouts, exceptions, data security, and high concurrency. Here is an optimized version of JSON server for you.
Read optimization points in advance
- with statement automatically closes socket: no need to manually try/finally close it to avoid resource leakage;
- Timeout Setting: Avoid infinite waiting for the server/client;
- Exception layered processing: distinguish JSON parsing errors, network timeouts, and other unknown errors;
- JSON Serialization: Structured transmission of data is much more convenient than plain text.
Optimized JSON server code
4. UDP vs TCP: Complete understanding with one table
5. Common UDP misunderstandings & tips
Q1: Is UDP really "completely unusable in scenarios that require reliability?"
no! The QUIC protocol (the bottom layer of HTTP/3) achieves the reliability of all TCP + the multiplexing of HTTP/2 on the basis of UDP - it is faster than TCP and also solves the head-of-line blocking problem of TCP.
Q2: How to improve the security of UDP program?
- Add data encryption: Use DTLS (UDP version of TLS);
- Add signature verification: Use HMAC to prevent data from being tampered with;
- Limit buffer size: To prevent attackers from sending oversized packets and causing buffer overflow;
- Add whitelist: Only allow access to specified IP/network segments.
Q3: Is UDP suitable for transferring large files?
It is not recommended to upload directly! If you must pass it, add it yourself:
- Fragmentation and reassembly mechanism (due to MTU limitation, a single UDP packet can transmit up to about 1472 bytes);
- Serial number (guaranteed sequence);
- Confirm retransmission mechanism (similar to TCP’s ACK).
6. Summary
UDP is not an "unreliable protocol", but a lightweight tool that can be chosen on demand - handing over complex choices to the application layer, in exchange for the ultimate improvement in real-time performance and efficiency.
Today we learned:
- Core features and applicable scenarios of UDP;
- The basic version of the Python UDP program that sends and receives;
- Produce a usable optimized version of JSON UDP server;
- UDP vs TCP comparison table;
- Common UDP misunderstandings and tips.
The next article can talk about UDP broadcast/multicast programming, or asyncio asynchronous UDP server. If you are interested, you can leave a message in the comment area~

