An asyncio stream is a high-level abstraction for creating and managing network connections and reading or writing sequential data. It hides socket details such as SSL handling and lost connections, making client-server applications easier to build and more robust. section 8.0 section 8.1
Stream APIs provide StreamReader for asynchronous reads and StreamWriter for writes. The open_connection coroutine creates both for a host and port. Reads can wait for a line or a specified number of bytes; writes require drain when buffered output must be flushed. section 8.3
Use streams to:
- Create HTTP clients that send requests and consume responses without blocking the event loop. section 8.3
- Process command-line input asynchronously while background tasks, such as multiple queries, continue running. section 8.0
- Create responsive servers and clients, including chat applications, with asyncio's start_server coroutine. section 8.7
Transports and protocols remain the lower-level foundation. They expose direct socket control through callbacks such as connection_made and data_received, whereas streams package common networking work into easier reader and writer interfaces. section 8.1 section 8.2
Asynchronous HTTP request
Call asyncio.open_connection, write an encoded HTTP request through StreamWriter, await drain, and repeatedly await StreamReader.readline until the response ends.
