Content · Programming · Python

Python Build an Async TCP Echo Server

An asyncio TCP server can accept local connections without allocating one thread per client. Define a stream handler, read bytes, write them back, drain output, and close the writer.

2 views Published Oct 18, 2026 Updated Oct 18, 2026 Admin

An asyncio TCP server can accept local connections without allocating one thread per client. Define a stream handler, read bytes, write them back, drain output, and close the writer.

What You Will Learn


This lesson focuses on Build an Async TCP Echo Server. You will connect the operation to a concrete input, inspect the result and identify the situation in which a different approach would be safer or clearer.

Asynchronous programming is useful when a program spends time waiting for other work, such as a socket or a remote service. One event loop can keep several operations in progress, provided each operation yields at an appropriate await point.

How It Works


The server binds to 127.0.0.1 for a safe local demonstration; production servers need access controls, framing rules, resource limits and often TLS.

Worked Example


The following example isolates the main behavior so you can run it from a local Python installation. Read the inputs first, then follow the operation and the final printed result.

import asyncio
async def echo(reader, writer):
    message = await reader.readline()
    writer.write(message)
    await writer.drain()
    writer.close()
    await writer.wait_closed()
async def main():
    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())

Understanding the Example


Start with the setup and import statements; these define the objects that the operation needs. Follow each assignment or function call in order, noting which arguments are provided and whether the operation creates a new value, changes existing state or returns a result. Finally, inspect the printed value or assertion rather than assuming that the operation worked.

The important behavior demonstrated here is: An asyncio TCP server can accept local connections without allocating one thread per client. Define a stream handler, read bytes, write them back, drain output, and close the writer. The example uses deliberately small values so the intermediate result is easy to reason about. A larger application must still handle validation, errors and resource cleanup.

Environment note: this example may require a separately installed package, local service, platform permission or network connection. Set up the indicated environment before running it; it has not been executed automatically for this guide.

When to Use This Approach


Use the design when the underlying operation is awaitable or when integrating with a well-defined async interface. For a single straightforward blocking task, regular synchronous code can be easier to maintain.

Important Behavior and Edge Cases


Leaving sockets open, omitting drain(), or assuming one read always returns a whole message.

Own the lifetime of tasks. Bound concurrency, observe exceptions, set appropriate deadlines and close resources after cancellation. A synchronous blocking function can still freeze an event loop.

Practice Exercise


Change the local echo service to prefix responses with ECHO: while preserving newline framing.

Before running your modified code, predict the output or expected failure. Confirm the result using at least one ordinary case and one invalid, missing or boundary input. If the operation accesses external resources, first exercise it against a controlled local or test environment.

Common Beginner Mistakes


  • Leaving sockets open, omitting drain(), or assuming one read always returns a whole message.
  • Own the lifetime of tasks. Bound concurrency, observe exceptions, set appropriate deadlines and close resources after cancellation. A synchronous blocking function can still freeze an event loop.

Key Takeaways


  • An asyncio TCP server can accept local connections without allocating one thread per client. Define a stream handler, read bytes, write them back, drain output, and close the writer.
  • Choose this technique for the problem it solves, but validate inputs and follow the cleanup and failure behavior shown above.
  • Next practice step: Change the local echo service to prefix responses with ECHO: while preserving newline framing.
Share this resourceSend this page to someone who may find it useful.