Manage Async Reader and Writer Lifetimes
Core idea
Asyncio streams expose StreamReader and StreamWriter for byte-oriented network I/O. open_connection supplies both; read(n) may return fewer bytes than requested and an empty result at EOF (for positive n). write queues bytes; await drain handles flow control. Close the writer in finally and await wait_closed. This lesson uses in-memory reader input and a fake writer, not a network connection.
import asyncio
async def main(): reader=asyncio.StreamReader() reader.feed_data(b'abcdef') reader.feed_eof() chunks=[] while chunk := await reader.read(4): chunks.append(chunk) print(chunks) print(reader.at_eof())
asyncio.run(main())The last chunk is shorter. feed_data and feed_eof simulate transport input for this example.
Expected output:
[b'abcd', b'ef']TrueTrace writer cleanup with a fake
import asyncio
async def main(): class FakeWriter: def write(self, data): print('write', data) async def drain(self): print('drain') def close(self): print('close') async def wait_closed(self): print('closed') async def send(writer): try: writer.write(b'OK') await writer.drain() finally: writer.close() await writer.wait_closed() await send(FakeWriter())
asyncio.run(main())This fake verifies call order, not transport behavior. Real callers obtain a StreamWriter from an established connection.
Expected output:
write b'OK'draincloseclosedCommon mistake
TCP is a byte stream, not a message queue; use a framing protocol such as a length prefix or newline-delimited records. drain is not an acknowledgement from the remote peer. Network cleanup can itself fail or be interrupted.
Practice
Adapt the fake to raise during drain and verify close and wait_closed still run. For an authorized local test service, use open_connection and apply the same lifetime pattern, without assuming message boundaries.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async streams
Check your understanding of async streams.
What is printed?
import asyncio
async def main(): r=asyncio.StreamReader() r.feed_data(b'abc'); r.feed_eof() print(await r.read(8))
asyncio.run(main())What is printed?
import asyncio
async def main(): r=asyncio.StreamReader() r.feed_eof() print(await r.read(1))
asyncio.run(main())What follows writer.write to respect flow control?
Does a successful drain prove remote application receipt?