Sub topic 13
TCP and UDP in code with sockets
This chapter assumes you know the layered network model, what an IP address and a packet are, and basic Python. It shows how the TCP and UDP behavior from earlier chapters appears in the sockets API.
Two socket types, two call sequences
A socket is the program's handle to a transport endpoint. You choose the protocol when you create it: SOCK_STREAM gives TCP and SOCK_DGRAM gives UDP.
| Step | TCP server | TCP client | UDP server | UDP client |
|---|---|---|---|---|
| Create | `socket(SOCK_STREAM)` | `socket(SOCK_STREAM)` | `socket(SOCK_DGRAM)` | `socket(SOCK_DGRAM)` |
| Set up | `bind`, `listen` | `connect` | `bind` | none |
| Exchange | `accept`, then `recv`/`sendall` | `sendall`/`recv` | `recvfrom`/`sendto` | `sendto`/`recvfrom` |
| End | `close` | `close` | `close` | `close` |
The TCP calls map to the handshake. connect starts the three-way handshake. accept returns a new socket for a connection whose handshake has already completed. The original listening socket stays open for more clients.
A TCP echo server
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 9000))
srv.listen()
conn, addr = srv.accept()
with conn:
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)SO_REUSEADDR lets you restart the server right away without an "address already in use" error caused by a previous connection lingering in TIME_WAIT. When recv returns an empty bytes object, the peer has closed its sending side. Use sendall rather than send, because send may transmit only part of the data and return the count it sent.
A TCP client and the byte stream
import socket
with socket.create_connection(("127.0.0.1", 9000)) as s:
s.sendall(b"hello ")
s.sendall(b"world")
s.shutdown(socket.SHUT_WR)
chunks = []
while True:
data = s.recv(1024)
if not data:
break
chunks.append(data)
print(b"".join(chunks))The two sendall calls may arrive as one recv or several. TCP preserves byte order but not message boundaries. The loop therefore reads until the server closes and joins the pieces. shutdown(SHUT_WR) sends a FIN while keeping the receive side open, so the client can still read the echo.
A UDP exchange
import socket
# Server (run in one process)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as srv:
srv.bind(("127.0.0.1", 9001))
data, addr = srv.recvfrom(2048)
srv.sendto(data, addr)
# Client (run in another process)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as cli:
cli.settimeout(2)
cli.sendto(b"ping", ("127.0.0.1", 9001))
try:
reply, _ = cli.recvfrom(2048)
print(reply)
except socket.timeout:
print("no reply")There is no connect or accept. Each sendto is one datagram, and recvfrom returns it whole along with the sender's address. If the buffer is smaller than the datagram, the excess is discarded. UDP never reports a lost datagram, so the client sets a timeout. Retrying, ordering, and duplicate detection are left to your application.
Common errors
- Connection refused. No process is listening on that port. Start the server first.
- Address already in use. An earlier socket still holds the port. Set
SO_REUSEADDRbeforebind. - Hung
recv. The program is waiting for data that was never sent, or a lost UDP datagram. Add a timeout. - Truncated or merged messages. The code treats TCP as message-based. Add framing.
Exercise
A TCP client calls sendall(b"abc") and then sendall(b"def"). The server's first recv(1024) returns b"abcdef". Is this a bug, and what should the server do if it needs the two messages separately?
Show answer
It is not a bug. TCP is a byte stream and does not keep message boundaries, so two writes can be delivered in one read. The protocol must mark boundaries itself, for example with a length prefix or a delimiter, and the server must read until it has a complete message.
Exercise
Why does the UDP client set a timeout, while the TCP client in this chapter does not need one to detect that the server has finished?
Show answer
UDP gives no delivery guarantee or notification, so a lost datagram would make recvfrom wait forever. TCP retransmits lost data and signals the end of the stream through an empty recv result when the peer closes.