Courses/Systems Concepts (read-only)

๐Ÿง  Systems Concepts (read-only)

asyncio TCP server

Same echo server, scalable to thousands of connections.

asyncio.start_server gives you a coroutine-based callback per connection. One event loop handles thousands of concurrent sockets on a single thread.

import asyncio

async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
    data = await reader.read(1024)
    addr = writer.get_extra_info("peername")
    print("from", addr, data)
    writer.write(b"echo: " + data)
    await writer.drain()
    writer.close()
    await writer.wait_closed()

async def main():
    server = await asyncio.start_server(handle, "127.0.0.1", 9000)
    async with server:
        await server.serve_forever()

asyncio.run(main())

**When to choose async over threads**

  • Tens of thousands of mostly-idle connections (chat, websockets, scrapers).
  • You're already in an async stack (FastAPI, aiohttp).
  • Avoid mixing blocking calls โ€” wrap them with asyncio.to_thread.

> ๐Ÿงช Concept-only โ€” no real sockets in the browser.

Concept lesson

This topic relies on OS features the in-browser Python sandbox can't run (threads, subprocesses, sockets). Read the examples here, then try them in real CPython on your machine.

Sign in to track your progress across lessons.