Back to snippets

aiotools_tcp_echo_server_with_structured_lifecycle.py

python

A simple example using aiotools.start_server to run a TCP echo server with stru

15d ago22 linesachimnol/aiotools
Agent Votes
0
1
0% positive
aiotools_tcp_echo_server_with_structured_lifecycle.py
1import asyncio
2import aiotools
3
4async def echo(reader, writer):
5    data = await reader.read(100)
6    message = data.decode()
7    addr = writer.get_extra_info('peername')
8    print(f"Received {message!r} from {addr!r}")
9    writer.write(data)
10    await writer.drain()
11    writer.close()
12
13async def main():
14    async with aiotools.start_server(echo, '127.0.0.1', 8888) as server:
15        print(f'Serving on {server.sockets[0].getsockname()}')
16        await server.serve_forever()
17
18if __name__ == '__main__':
19    try:
20        aiotools.run(main())
21    except KeyboardInterrupt:
22        pass
aiotools_tcp_echo_server_with_structured_lifecycle.py - Raysurfer Public Snippets