Created
February 8, 2020 15:33
-
-
Save mfonism/f94f5d7d2b1d24504da0704e4643dd8a to your computer and use it in GitHub Desktop.
A simple server with asyncio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| async def handle_request(reader, writer): | |
| data = await reader.read(1024) | |
| 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 main(): | |
| server = await asyncio.start_server(handle_request, "127.0.0.1", 8888) | |
| addr = server.sockets[0].getsockname() | |
| print(f"Serving on {addr}") | |
| async with server: | |
| await server.serve_forever() | |
| try: | |
| asyncio.run(main()) | |
| except KeyboardInterrupt: | |
| pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment