0
0
PythonComparisonBeginner · 4 min read

TCP vs UDP in Python: Key Differences and When to Use Each

In Python, TCP is a connection-oriented protocol that ensures reliable data transfer, while UDP is connectionless and faster but does not guarantee delivery. Use socket.SOCK_STREAM for TCP and socket.SOCK_DGRAM for UDP when creating sockets.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of TCP and UDP in Python.

FeatureTCPUDP
TypeConnection-orientedConnectionless
ReliabilityGuaranteed deliveryNo guarantee of delivery
OrderingData arrives in orderData may arrive out of order
SpeedSlower due to overheadFaster with less overhead
Use caseWeb, file transfer, emailStreaming, gaming, DNS
Python socket typesocket.SOCK_STREAMsocket.SOCK_DGRAM
⚖️

Key Differences

TCP (Transmission Control Protocol) creates a reliable connection between two endpoints before data is sent. It ensures that all data packets arrive correctly and in order by using acknowledgments and retransmissions. This makes it ideal for applications where accuracy matters, like web browsing or file transfers.

UDP (User Datagram Protocol) sends data without establishing a connection. It does not check if packets arrive or if they arrive in order, which reduces overhead and increases speed. This makes UDP suitable for real-time applications like video streaming or online gaming where speed is more important than perfect accuracy.

In Python, you specify the protocol when creating a socket: socket.SOCK_STREAM for TCP and socket.SOCK_DGRAM for UDP. TCP sockets require a connection setup with connect() or accept(), while UDP sockets send data directly with sendto() and receive with recvfrom().

⚖️

Code Comparison

Below is a simple Python example showing a TCP server receiving a message from a TCP client.

python
import socket

# TCP Server
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(1)

print('TCP Server waiting for connection...')
conn, addr = server_socket.accept()
print(f'Connected by {addr}')
data = conn.recv(1024)
print('Received:', data.decode())
conn.sendall(b'Hello TCP Client')
conn.close()
server_socket.close()
Output
TCP Server waiting for connection... Connected by ('127.0.0.1', 54321) Received: Hello TCP Server
↔️

UDP Equivalent

Here is the UDP version of the same task: a server receiving a message and replying.

python
import socket

# UDP Server
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('localhost', 12345))

print('UDP Server waiting for message...')
data, addr = server_socket.recvfrom(1024)
print(f'Received from {addr}:', data.decode())
server_socket.sendto(b'Hello UDP Client', addr)
server_socket.close()
Output
UDP Server waiting for message... Received from ('127.0.0.1', 54321): Hello UDP Server
🎯

When to Use Which

Choose TCP when you need reliable communication where every message must arrive intact and in order, such as loading web pages, sending emails, or transferring files. TCP handles errors and resends lost data automatically.

Choose UDP when speed is critical and occasional data loss is acceptable, like in live video streaming, online gaming, or voice calls. UDP reduces delay by skipping connection setup and error checking.

Key Takeaways

Use TCP in Python with socket.SOCK_STREAM for reliable, ordered data transfer.
Use UDP in Python with socket.SOCK_DGRAM for faster, connectionless communication.
TCP guarantees delivery and order but is slower due to overhead.
UDP is faster but does not guarantee delivery or order.
Pick TCP for accuracy and UDP for speed depending on your application's needs.