Python 使用 Asyncio 构建 TCP 应用

import asyncio

async def handle_echo(reader, writer):
    while True:
        # 判断EOF结束符关闭链接
        if reader.at_eof():
            break
        data = await reader.readline()
        message = data.decode()
        addr = writer.get_extra_info('peername')

        print(f"Received {message!r} from {addr!r}")

        print(f"Send: {message!r}")
        writer.write(data)
        await writer.drain()

    print("Close the connection")
    writer.close()

async def tcp_server_task():
    server = await asyncio.start_server(handle_echo, '127.0.0.1', 8888)

    addr = server.sockets[0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()

async def main():
    task = asyncio.create_task(tcp_server_task())
    await task

asyncio.run(main())