Middle+
What are the main differences between TCP and UDP, and when should each protocol be chosen?
sobes.tech AI
Answer from AI
Main differences between TCP and UDP:
- TCP (Transmission Control Protocol) — connection-oriented, provides reliable data delivery, error checking, delivery order, and flow control.
- UDP (User Datagram Protocol) — connectionless, does not guarantee delivery, order, or integrity, but is faster and has lower overhead.
When to choose:
- TCP is suitable for applications where reliability and order are important, such as web servers, databases, email.
- UDP is used where speed and low latency are crucial, and packet loss is acceptable, such as streaming video, online gaming, DNS queries.
Example of UDP usage in Go:
conn, err := net.Dial("udp", "example.com:1234")
if err != nil {
// handle error
}
_, err = conn.Write([]byte("data"))
TCP in Go:
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
// handle error
}
_, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"))
The choice depends on reliability and performance requirements.