Middle
What are TCP and UDP, and what is the difference?
sobes.tech AI
Answer from AI
TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are transport layer protocols used for data transmission over a network.
TCP:
- Reliable, connection-oriented.
- Guarantees data delivery in the correct order.
- Uses acknowledgments (ACK), retransmits lost packets.
- Suitable for applications where data integrity is important (e.g., HTTP, FTP).
UDP:
- Connectionless, unreliable.
- Does not guarantee delivery or packet order.
- Lower latency and overhead.
- Used where speed is crucial and some data loss is acceptable (e.g., streaming, online gaming, DNS).
Example in Go for creating a UDP server:
package main
import (
"fmt"
"net"
)
func main() {
addr := net.UDPAddr{
Port: 12345,
IP: net.ParseIP("0.0.0.0"),
}
conn, err := net.ListenUDP("udp", &addr)
if err != nil {
panic(err)
}
defer conn.Close()
buf := make([]byte, 1024)
for {
n, clientAddr, err := conn.ReadFromUDP(buf)
if err != nil {
fmt.Println("Error:", err)
continue
}
fmt.Printf("Received %s from %s\n", string(buf[:n]), clientAddr)
}
}