Sub topic 15
Network clients and servers with streams
This chapter assumes you can write coroutines, start them with asyncio.run, run them together with tasks or gather, and use asyncio.timeout. You should also know basic TCP terms: host, port, connection, and byte stream.
Why streams exist
A TCP connection is a stream of bytes with no message boundaries. asyncio offers two APIs for network code:
- Protocols and transports are callback-based, low-level, and fast.
- Streams are
async/awaitwrappers around them. You callawait reader.readline()and the event loop runs other tasks while the bytes arrive.
Streams are the right default for application code. Use protocols only when you need to control buffering or per-packet callbacks.
A stream connection has two objects:
| Object | Class | Purpose |
|---|---|---|
| `reader` | `asyncio.StreamReader` | Awaitable read methods |
| `writer` | `asyncio.StreamWriter` | Buffered writes, `drain`, close |
Both sides of a connection get this pair. The client gets it from asyncio.open_connection. The server gets it as the arguments of your handler coroutine.
A first server and client
The program below starts a server on a free port and connects two clients to it in the same process. That keeps the example self-contained.
import asyncio
async def handle(reader, writer):
while True:
line = await reader.readline()
if not line: # b"" means the peer closed the connection
break
writer.write(line.upper())
await writer.drain()
writer.close()
await writer.wait_closed()
async def client(port, text):
reader, writer = await asyncio.open_connection("127.0.0.1", port)
writer.write(text.encode() + b"\n")
await writer.drain()
reply = await reader.readline()
print(reply.decode().strip())
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(handle, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
async with server:
await asyncio.gather(client(port, "hello"), client(port, "world"))
asyncio.run(main())The output is HELLO and WORLD. Their order can vary, because the two clients run concurrently.
Points to notice:
- Port
0asks the operating system for any free port. Read the real one fromserver.sockets. start_servercallshandleonce per connection. Each call runs as its own task, so one slow client does not block the others.async with servercloses the server when the block exits. To run forever, useawait server.serve_forever()instead.
Writing: `write` is not a coroutine
writer.write(data) is an ordinary function. It copies the bytes into an internal buffer and returns immediately. The loop sends the buffer when the socket is ready. If a peer reads slowly, the buffer grows without limit unless you wait on drain.
await writer.drain() pauses your coroutine while the buffer is above a high-water mark. It is how streams apply backpressure, in the same way a bounded asyncio.Queue does. It also raises ConnectionResetError if the peer has gone away.
Reading: pick the method that matches your framing
Because TCP has no message boundaries, one send on the peer can arrive as several reads, and several sends can arrive as one. Your protocol must define where a message ends. StreamReader offers a method for each common choice:
| Method | Returns | Use when |
|---|---|---|
| `read(n)` | Up to `n` bytes, as soon as any are available | Copying data without caring about boundaries |
| `read()` | Everything until EOF | The peer closes to mark the end |
| `readline()` | Bytes up to and including `\n` | Text protocols, one message per line |
| `readuntil(sep)` | Bytes up to and including `sep` | Custom delimiters such as `\r\n\r\n` |
| `readexactly(n)` | Exactly `n` bytes | Fixed-size headers and length-prefixed messages |
Each of these returns b"" or raises at end of input. When the connection closes early, readexactly and readuntil raise asyncio.IncompleteReadError. That exception has a partial attribute holding whatever bytes arrived. Treat it as the normal way to detect a disconnect in binary protocols.
Each stream has a buffer limit, 64 KiB by default. If readline or readuntil sees more data than the limit without finding the delimiter, it raises ValueError (it wraps LimitOverrunError). Pass limit= to start_server or open_connection to change it. This limit protects your server from a client that never sends a newline.
Length-prefixed messages
Lines are fine for text. For binary data, a common choice is a length prefix: a fixed-size header that says how many bytes follow. readexactly makes this easy.
import asyncio
import struct
MAX_SIZE = 1_000_000
async def send(writer, payload: bytes):
writer.write(struct.pack("!I", len(payload)) + payload)
await writer.drain()
async def receive(reader) -> bytes:
header = await reader.readexactly(4)
(length,) = struct.unpack("!I", header)
if length > MAX_SIZE:
raise ValueError(f"message too large: {length}")
return await reader.readexactly(length)
async def handle(reader, writer):
try:
while True:
message = await receive(reader)
await send(writer, message[::-1])
except asyncio.IncompleteReadError:
pass # client disconnected
finally:
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(handle, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
async with server:
reader, writer = await asyncio.open_connection("127.0.0.1", port)
for text in ("abc", "streams"):
await send(writer, text.encode())
print((await receive(reader)).decode())
writer.close()
await writer.wait_closed()
asyncio.run(main())This prints cba and then smaerts. The "!I" format means a 4-byte unsigned integer in network (big-endian) byte order. The MAX_SIZE check matters for security. Without it, a client could send a header claiming 4 GB and make your server wait for, and buffer, that much data.
Timeouts on network calls
A peer can stop responding without closing the connection. A read with no timeout then waits forever. Wrap network calls in asyncio.timeout:
import asyncio
async def silent(reader, writer):
await reader.read() # wait until the client disconnects
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(silent, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
async with server:
reader, writer = await asyncio.open_connection("127.0.0.1", port)
try:
async with asyncio.timeout(0.5):
await reader.readline()
except TimeoutError:
print("no reply within 0.5s")
finally:
writer.close()
await writer.wait_closed()
asyncio.run(main())The timeout cancels the pending readline, and the async with block turns that cancellation into TimeoutError. You can also wrap open_connection to limit how long connecting may take.
Closing connections correctly
Closing takes two steps:
writer.close()starts closing and returns immediately.await writer.wait_closed()waits until the connection is closed.
Skipping the second step can leave a "transport closed" warning, or lose buffered data in short-lived programs. Put both in a finally block so errors do not leak sockets. If you need to be sure the peer has received everything, drain before closing.
Handler coroutines should never let an exception escape unnoticed. An unhandled exception in a handler is logged by the loop and the connection is dropped. It is better to catch the errors you expect, such as IncompleteReadError, ConnectionResetError, and your own protocol errors, and close the writer in finally.
Serving many clients
Each connection runs in its own task, so shared state is safe from data races between statements but not between await points. A chat server that keeps a set of writers must update the set in the handler and handle writers that fail mid-broadcast. To cap load, wrap the body of the handler in an asyncio.Semaphore, or count connections yourself and refuse new ones. Do blocking work, such as CPU-heavy parsing, with asyncio.to_thread or a process pool, because it stalls every connection otherwise.
Common mistakes
- Treating one read as one message.
read(100)may return 3 bytes. Frame messages with lines, delimiters, or length prefixes. - Ignoring EOF. A loop that never checks for
b""spins forever after the client disconnects. - Skipping
drain. Memory grows when the peer reads slowly. - No timeouts. One stalled peer holds a task and a socket indefinitely.
- Trusting declared sizes. Check lengths before calling
readexactly. - Forgetting
wait_closed. Sockets and warnings accumulate.
Exercise
A server handler does data = await reader.read(1024) and then treats data as one complete JSON message. It works on a laptop but fails sometimes in production. Why, and how would you fix it?
Show answer
TCP is a byte stream, so read(1024) returns whatever has arrived, which may be part of a message or several messages. On a local network the message often arrives in one piece, which hides the bug. Add framing. For example, send one JSON document per line and use readline(). Or send a 4-byte length prefix and use readexactly. Also check for b"" as end of input, enforce a maximum size, and wrap the read in asyncio.timeout.
Exercise
Write the shape of a handler that echoes lines back, stops cleanly when the client disconnects, and gives up on clients that send nothing for 30 seconds.
Show answer
Loop with async with asyncio.timeout(30): line = await reader.readline() inside a try block. If line is b"", break. Otherwise call writer.write(line) and await writer.drain(). Catch TimeoutError and ConnectionResetError to leave the loop. In finally, call writer.close() and await writer.wait_closed().