Sub topic 15
Network clients and servers with streams
This chapter assumes you can write coroutines with async def and await, start them with asyncio.run, and use async with. Streams are the high-level asyncio API for TCP connections. They let you read and write bytes with await and without callbacks.
The stream objects
A TCP connection gives you two objects:
StreamReaderreads incoming bytes. Its main methods areread(n),readline(),readexactly(n)andreaduntil(sep). All of them are coroutines.StreamWritersends bytes.write(data)is a normal function that buffers the data.drain()is a coroutine that waits until the buffer is small enough to continue.close()starts shutdown, andwait_closed()waits for it to finish.
A client gets this pair from asyncio.open_connection(host, port). A server passes the pair to a handler coroutine that you give to asyncio.start_server. The server runs that handler as a separate task for each connection, so many clients are served at once on one thread.
A complete echo example
This script starts a server that upper-cases each line it receives. It then connects a client to it, all in one process. Port 0 asks the operating system for a free port.
import asyncio
async def handle(reader, writer):
while line := await reader.readline():
writer.write(line.upper())
await writer.drain()
writer.close()
await writer.wait_closed()
async def client(port):
reader, writer = await asyncio.open_connection("127.0.0.1", port)
for word in ("hello", "streams"):
writer.write(word.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 client(port)
asyncio.run(main())The output is HELLO and then STREAMS.
How the example works
start_serverbegins listening. For every new connection it creates a task that runshandle(reader, writer).readline()suspends the handler until a full line arrives. While it waits, the event loop runs other handlers.readline()returns an emptybytesobject when the client closes its side. The walrus loop treats that as false and stops.async with servercloses the listening socket when the block exits. In Python 3.12 and later it also waits for open connections to finish, which is why the handler closes the writer.
To run a server until you stop it, replace the client call with await server.serve_forever().
Common mistakes
- Skipping
drain().write()only copies bytes into a buffer. If a peer reads slowly and you never awaitdrain(), memory use grows without limit. - Forgetting to encode. Streams carry
bytes. Call.encode()before writing and.decode()after reading. - Assuming one
read()equals one message. TCP is a byte stream.read(100)can return fewer bytes than you sent in one write, or pieces of two writes. Usereadline(),readuntil(), orreadexactly()with a length prefix to find message boundaries. - Waiting forever on a silent peer. Wrap reads in
asyncio.timeout()so a stalled connection does not hold a handler forever. - Not closing the writer. Always call
close()andawait wait_closed(), ideally intry/finally, so errors do not leak sockets.
Exercise
A client sends the bytes b"abc" in one write and b"def" in another. The server calls await reader.read(6). Is it guaranteed to return b"abcdef"? Which reader method would guarantee it?
Show answer
No. read(6) returns up to 6 bytes and may return only b"abc" if the second write has not arrived yet. await reader.readexactly(6) waits until exactly six bytes have arrived. It raises IncompleteReadError if the connection closes first.