Created
November 10, 2023 20:39
-
-
Save EteimZ/7d0fda31e8787b43594b3e6b006b659f to your computer and use it in GitHub Desktop.
A simple webserver built 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.readuntil(separator=b"\r\n\r\n") | |
| message = data.decode() | |
| addr = writer.get_extra_info('peername') | |
| print(f"Received request from {addr}") | |
| print(f"Send response.") | |
| writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nHello, World") | |
| await writer.drain() | |
| print("Close the connection") | |
| writer.close() | |
| await writer.wait_closed() | |
| async def main(): | |
| server = await asyncio.start_server( | |
| handle_request, '127.0.0.1', 8888) | |
| addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets) | |
| print(f'Serving on {addrs}') | |
| async with server: | |
| await server.serve_forever() | |
| if __name__ == '__main__': | |
| try: | |
| asyncio.run(main()) | |
| except KeyboardInterrupt: | |
| print("Server closed!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment