Sub topic 3
Flow Control, TCP States, and Choosing TCP or UDP
Assume you know the layered network model, IP addresses, packets, and basic Python. This chapter focuses on how endpoints regulate traffic and how these ideas appear in socket programs.
Flow control and the receive window
Flow control prevents a fast sender from overrunning a slow receiver. TCP advertises a receive window, or rwnd, in its acknowledgments. The value tells the sender how many more bytes the receiver can accept.
The sender keeps unacknowledged data within that window. If the receiver’s buffer fills, it can advertise a zero window. The sender pauses and periodically checks whether space is available again.
Flow control protects one receiver. Congestion control protects the network. TCP maintains a congestion window, cwnd, based on signs of network capacity. The usable sending limit is approximately:
min(rwnd, cwnd)
Congestion control
TCP begins with slow start, increasing cwnd quickly as acknowledgments arrive. Despite its name, this phase can grow exponentially. After reaching a threshold, TCP uses congestion avoidance, increasing the window more slowly, usually about one segment per round-trip time.
Loss, detected through a timeout or repeated duplicate acknowledgments, suggests congestion. TCP reduces its sending rate and grows again. This adapts each connection to changing network conditions.
Closing a connection and TCP states
TCP closes each direction independently. One endpoint sends FIN; the peer acknowledges it and later sends its own FIN. The first endpoint acknowledges that FIN. The endpoint that actively closes usually enters TIME_WAIT, retaining connection information briefly so delayed segments cannot corrupt a new connection.
TCP and UDP in code with sockets
TCP uses connect, listen, and accept. It provides a byte stream. UDP uses sendto and recvfrom; each operation handles one datagram.
import socket
# TCP client
with socket.create_connection(("127.0.0.1", 9000)) as tcp:
tcp.sendall(b"hello")
print(tcp.recv(1024))
# UDP client
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp:
udp.settimeout(2)
udp.sendto(b"ping", ("127.0.0.1", 9001))
print(udp.recvfrom(1024)[0])Choosing between TCP and UDP
| Need | Better default | Reason |
|---|---|---|
| Complete, ordered data | TCP | Reliability is built in |
| Timely independent messages | UDP | The application controls recovery and timing |
| Streaming media or games | UDP | Old data may be less useful than current data |
Choose UDP only when the application can handle its missing guarantees.
Exercise
If a TCP receiver advertises a zero receive window, should the sender immediately send more data?
Show answer
No. It should wait and probe later, because flow control says the receiver has no buffer space.