02 / Networks / 35 min READ + PRACTICE
TCP clients and servers.
Understand connections, streams, buffering and safe loopback socket experiments.
A connection is a byte stream
TCP preserves ordering, but recv() does not promise a whole message. Design a delimiter or length prefix before sending structured data. Put a timeout on both ends and limit input size; a peer may send nothing or disconnect halfway through.
Start a loopback echo service
Run this in one terminal. The binding address limits the listener to your own machine. The server handles one client and then exits.
import socket
with socket.socket() as server:
server.bind(('127.0.0.1', 9001))
server.listen(1)
conn, addr = server.accept()
with conn:
conn.settimeout(3)
data = conn.recv(256)
conn.sendall(data.upper()) Connect from a second terminal
Save this as a separate file and run it while the server is waiting. Change the message, then try connecting after the server has exited and handle ConnectionRefusedError.
import socket
with socket.create_connection(('127.0.0.1', 9001), timeout=3) as client:
client.sendall(b'hello lab')
print(client.recv(256).decode()) Try it in your lab
Extend the service with a newline-delimited message and a 256-byte limit. Verify a second connection fails cleanly after the one-shot server exits.
Make sure it clicks
Why is a single recv(256) not a general solution for reading a complete TCP message?
A prompt you can adapt
Refactor my loopback TCP echo exercise into two small Python files, add timeouts and tests for connection-refused behavior.How to set up OpenCode ↗