A socket timeout limits how long one receive waits for data; it does not define a whole-request deadline.
Python socket idle timeout: bound one blocking receive
Operation contract
A local socket pair has no incoming byte at first, so recv raises a timeout. The peer then sends one byte, and the next receive succeeds. This shows the per-operation idle boundary without contacting a remote host. A framed protocol still needs length limits and enough reads to assemble a message.
Failure and ownership boundary
Repeated successful one-byte receives can extend total elapsed time indefinitely. Track an overall deadline separately, validate frame length before allocation, and close both sockets on every path. Socket pair availability and exact timing vary by platform; the fixture checks only local stream behavior.
Working program
import socket
reader, writer = socket.socketpair()
with reader, writer:
reader.settimeout(0.02)
try:
reader.recv(1)
except socket.timeout:
print("idle_timeout", True)
writer.sendall(b"R")
print("received", reader.recv(1).decode("ascii"))Output
idle_timeout True
received RCosts and limits
The fixture waits about 20 milliseconds for the empty receive. Repeated timeouts or tiny reads can still waste CPU and connections without a total deadline.
Common Mistakes
- An idle timeout is not an overall request deadline.
- One recv is not one application message.
- Always close both socket owners after a failed read.
