Echo in Python Concurrency with asyncio

Overview

The echo coroutine is a fundamental component in building an echo server using Python's asyncio library. Its primary responsibility is to handle data from a client connection. The coroutine operates in a loop, continuously receiving data from the client and sending it back, effectively echoing the data. This behavior is typical in echo servers, where the server simply sends back whatever data it receives from the client.

Building an asyncio Echo Server

The following code demonstrates how to build an echo server using asyncio. This server listens for incoming connections and creates a new task to handle each connection using the echo coroutine.

[Listing 3.8 Building an asyncio echo server](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-3/108)

import asyncio
import socket
from asyncio import AbstractEventLoop

async def echo(connection: socket, loop: AbstractEventLoop) -> None:
    while data := await loop.sock_recv(connection, 1024):                #1
        await loop.sock_sendall(connection, data)                        #2
 
async def listen_for_connection(server_socket: socket, loop: AbstractEventLoop):
    while True:
        connection, address = await loop.sock_accept(server_socket)
        connection.setblocking(False)
        print(f"Got a connection from {address}")
        asyncio.create_task(echo(connection, loop))                      #3
 
async def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 
    server_address = ('127.0.0.1', 8000)
    server_socket.setblocking(False)
    server_socket.bind(server_address)
    server_socket.listen()
 
    await listen_for_connection(server_socket, asyncio.get_event_loop()) #4
 
asyncio.run(main())
  • #1: The echo coroutine loops forever, waiting for data from a client connection.
  • #2: Once data is received, it is sent back to the client.
  • #3: For each new connection, an echo task is created to handle client data.
  • #4: The coroutine to listen for connections is started.

Graceful Shutdown

Handling shutdowns gracefully is crucial in server applications to ensure that all resources are properly released and that no data is lost. The following code extends the echo server to handle shutdowns gracefully.

[Listing 3.10 A graceful shutdown](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-3/150)

import asyncio
from asyncio import AbstractEventLoop
import socket
import logging
import signal
from typing import List

async def echo(connection: socket, loop: AbstractEventLoop) -> None:
    try:
        while data := await loop.sock_recv(connection, 1024):
            print('got data!')
            if data == b'boom\r\n':
                raise Exception("Unexpected network error")
            await loop.sock_sendall(connection, data)
    except Exception as ex:
        logging.exception(ex)
    finally:
        connection.close()

echo_tasks = []

async def connection_listener(server_socket, loop):
    while True:
        connection, address = await loop.sock_accept(server_socket)
        connection.setblocking(False)
        print(f"Got a connection from {address}")
        echo_task = asyncio.create_task(echo(connection, loop))
        echo_tasks.append(echo_task)

class GracefulExit(SystemExit):
    pass

def shutdown():
    raise GracefulExit()

async def close_echo_tasks(echo_tasks: List[asyncio.Task]):
    waiters = [asyncio.wait_for(task, 2) for task in echo_tasks]
    for task in waiters:
        try:
            await task
        except asyncio.exceptions.TimeoutError:
            # We expect a timeout error here
            pass

async def main():
    server_socket = socket.socket()
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    server_address = ('127.0.0.1', 8000)
    server_socket.setblocking(False)
    server_socket.bind(server_address)
    server_socket.listen()

    for signame in {'SIGINT', 'SIGTERM'}:
        loop.add_signal_handler(getattr(signal, signame), shutdown)
    await connection_listener(server_socket, loop)

loop = asyncio.new_event_loop()

try:
    loop.run_until_complete(main())
except GracefulExit:
    loop.run_until_complete(close_echo_tasks(echo_tasks))
finally:
    loop.close()

In this implementation:

  • The echo coroutine now includes error handling to log exceptions and ensure connections are closed properly.
  • A list echo_tasks is maintained to keep track of all active echo tasks.
  • A custom exception GracefulExit is used to signal a shutdown.
  • The shutdown function raises the GracefulExit exception when a termination signal is received.
  • The close_echo_tasks coroutine attempts to close all echo tasks gracefully, allowing them a timeout period to complete.

Multithreaded Echo Server

The echo function can also be used in a multithreaded echo server context. In this model, the function runs in a separate thread for each client connection, demonstrating the thread-per-connection model. This approach contrasts with the asyncio model, where tasks are used to handle concurrency within a single thread.

FAQ (Frequently asked questions)