TCP
(Transmission Control Protocol) is a connection-oriented protocol in which the data can be transferred bidirectionally.
UDP
(User Datagram Protocol) is a connectionless protocol in which data is sent in datagrams.
Let’s talk about the differences between them and how to choose them correctly according to scenarios.
1. The differences
1.1 Protocol
TCP
is a connection-oriented protocol, which means before peers need to establish a connection before they begin to exchange data. This procedure is called TCP 3-way handshake.
During the whole process of data transmission, the connection’s state needs to be maintained until the termination. The peers go through a process of TCP 4-way handshake to disconnect the connection.
UDP
is a datagram oriented protocol. It is much more lightweight than TCP. UDP
is designed as close as to plain IP as possible. There is no connection during data transmission. Because of this, one peer could send data to multiple targets at one time.
1.2 Transmission reliability
TCP
make checks for errors and try to fix them. TCP is designed to provide a
**”reliable stream”**. There is an acknowledgment for every segment transferred. The sender will retry to deliver it if there is any segment without a response. There is a strategy of flow control
to control the sending speed, make sure the receiver could process received data properly.
UDP
have a checksum for the data but there is no guarantee of delivery, ordering, or duplicate protection. The application layer track lost packets and to recover from losses.
1.3 Performance
Because UDP
does not need to maintain the states of connection, the transmission speed is better than TCP
?
The answer depends on whether there are packet losses.
When a packet is lost during the transmission, TCP retransmission timeouts start to introduce delays and make a difference in the time performance.
Since UDP
ignore losses, many parts of time could be saved.
1.4 Header Size
TCP
header: 20 Bytes, UDP
header: 8 Bytes.
2. When to use TCP?
Most networking applications use TCP
, such as Web browser, Email, FTP. It’s better to choose TCP
whenever data losses can not be accepted.
3. When to use UDP?
In real-world applications, UDP
is adopted in limited scenarios. It is OK to use UDP
when application accept some packet loss, reordering, errors or duplication.
Typically, Domain Name System (DNS), Dynamic Host Configuration Protocol (DHCP), voice and video applications use UDP
.
If you need the reliability, there are some open-source projects(such as rudp) provide a reliable transmission on UDP
.
Others
In Portable Operating System Interface (POSIX), TCP
and UDP
will pass different for function of socket
.
|
Here are simple demo implementations for UDP Server-Client and TCP Server-Client.
References
Join my Email List for more insights, It's Free!😋