First, What Is It
- Transport layer protocols: decide "which program gets the data" and "how it is delivered".
- TCP: connection-oriented and reliable — like registered mail (receipt, in order, retransmission on loss).
- UDP: connectionless and unreliable — like regular mail (sent and forgotten; fast but not guaranteed).
- Socket: the SDK provides BSD-like socket APIs, nearly identical to PC network programming.
Breaking Down the Principle
1. TCP Three-Way Handshake and Four-Way Wave
Why "three"? Both sides must confirm they can send and receive and agree on sequence numbers, avoiding stale connection remnants.
2. Client / Server Socket Flow
The client actively connects; the server passively accepts; then both send/recv.
3. UDP: Connectionless Datagrams
UDP needs no handshake — just sendto and recvfrom — and natively supports broadcast (255.255.255.255) and multicast. Suitable for real-time scenarios like audio/video and device discovery.
4. Ports and Reliability
- Ports identify "which program" (0~65535).
- TCP reliability: sequence numbers + ACK + timeout retransmission + sliding window.
- UDP has none of these; the application handles loss/ordering itself.
How the SDK Implements It
- Related pages: TCP Client, TCP Server, UDP Client, UDP Broadcast
SDK client flow (lwIP socket API):
int sock = socket(AF_INET, SOCK_STREAM, 0); /* SOCK_STREAM for TCP, SOCK_DGRAM for UDP */
connect(sock, (struct sockaddr *)&dest, sizeof(dest));
send(sock, buffer, len, 0);
recv(sock, buffer, sizeof(buffer), 0);
close(sock);The server adds bind + listen + accept. That is exactly the difference between the "server" and "client" examples.
Common Exam & Interview Questions
Why does TCP need a three-way handshake?
So both sides confirm send/receive capability and synchronize initial sequence numbers, preventing stale connection requests from causing confusion; two is not enough, four is redundant.
When to choose TCP vs UDP?
TCP for reliable delivery (files, web pages, MQTT); UDP for real-time/broadcast (audio/video, device discovery, games).
How do client and server program flows differ?
Client: socket→connect→send/recv; server: socket→bind→listen→accept→recv/send. The difference is bind/listen/accept.
Does UDP guarantee delivery?
No. UDP has no ACK/retransmission; packets may be lost or reordered. For reliability use TCP or add application-level acknowledgment.
What are ports for?
IP finds the device; the port finds the specific program on it; both TCP and UDP headers carry source/destination ports.
Have questions?
For any other questions, visit the unified Q&A and discussion board: Ai-Thinker Discussions

