asyncio.
Understanding the Concept
asyncio.open_connection establishes an asynchronous TCP stream and returns reader and writer objects. Handle server errors, closing and connection timeouts.
Bind to loopback for local experiments; avoid exposing test servers on public interfaces.
How the event loop makes progress
When a coroutine reaches await, it may suspend so another ready Task can execute. This scheduling is cooperative: blocking operations that do not yield hold up every coroutine sharing the event loop. Assign ownership of background tasks, put timeouts around operations that may wait, and release resources on cancellation.
An async function does not automatically use several CPU cores. Use async-compatible I/O for waiting tasks and executors or separate processes for blocking or CPU-heavy work when appropriate.
Worked Example
Read the code from the first line to the last. Identify which values are inputs, which operation is being demonstrated and what should happen before running it.
import asyncio
async def main():
async def echo(reader, writer):
text = await reader.readline()
writer.write(text)
await writer.drain()
writer.close()
server = await asyncio.start_server(echo, "127.0.0.1", 0)
try:
port = server.sockets[0].getsockname()[1]
reader, writer = await asyncio.open_connection("127.0.0.1", port)
writer.write(b"hello\n")
await writer.drain()
print((await reader.readline()).decode().strip())
writer.close()
await writer.wait_closed()
finally:
server.close()
await server.wait_closed()
asyncio.run(main())
Walkthrough: What Each Part Does
- The central operation is asyncio.open_connection('127.0.0.1', port). Read its actual arguments: those values determine what is tested, logged, measured or scheduled. Then locate the line that inspects its result or handles a failure.
- The imports make asyncio available. These are standard-library building blocks unless the example explicitly names an external tool.
- The definition main creates reusable behavior. Its body runs when called, awaited or instantiated; defining it alone does not run the body of an ordinary function.
- Each await is a suspension point. When the awaited operation is not ready, the loop can schedule other tasks instead of blocking the entire thread.
- The try/except or finally block states what happens when an operation fails; cleanup and error reporting are part of the example, not optional extras.
This demonstration focuses on one practical behavior. Before changing several lines, vary one input or one configuration choice and check whether the result changes for the reason you expected.
The example uses terminal, platform, external tool or process behavior that was not exercised automatically. Run it only in a suitable environment after reviewing the shown permissions and paths.
Important Behavior and Edge Cases
Assuming a TCP read always returns a complete message or leaving StreamWriter open after use.
Bind to loopback for local experiments; avoid exposing test servers on public interfaces.
Practice Exercise
Change the echo server to return upper-case text and set a timeout on the read.
Write down the result you expect before running your changed code. Check at least one normal case and one boundary or failure case. If your example starts workers or opens resources, verify how they are cleaned up.
Further reading: official documentation and API reference.
Common Beginner Mistakes
- Assuming a TCP read always returns a complete message or leaving StreamWriter open after use.
- Calling a blocking function inside the event loop, or creating tasks without awaiting, cancelling or owning them.
Key Takeaways
- asyncio.
- Bind to loopback for local experiments; avoid exposing test servers on public interfaces.
- Practice: Change the echo server to return upper-case text and set a timeout on the read.