|
| 1 | +import asyncio |
| 2 | +import urllib.request |
| 3 | +import urllib.error |
| 4 | +import sys |
| 5 | + |
| 6 | + |
| 7 | +async def fetch_url(url): |
| 8 | + """Fetches a URL using urllib.request in a non-blocking way.""" |
| 9 | + try: |
| 10 | + # urlopen is blocking, so run it in a thread pool executor |
| 11 | + response_obj = await asyncio.to_thread(urllib.request.urlopen, url) |
| 12 | + with response_obj as response: |
| 13 | + return response.read().decode( |
| 14 | + "utf-8", errors="ignore" |
| 15 | + ) # Use errors='ignore' for robust decoding |
| 16 | + except urllib.error.URLError as e: |
| 17 | + return f"Error fetching {url}: {e.reason}" |
| 18 | + except Exception as e: |
| 19 | + return f"An unexpected error occurred while fetching {url}: {e}" |
| 20 | + |
| 21 | + |
| 22 | +async def handle_client(reader, writer): |
| 23 | + addr = writer.get_extra_info("peername") |
| 24 | + print(f"Connection from {addr}") |
| 25 | + |
| 26 | + try: |
| 27 | + request_data = await reader.read( |
| 28 | + 4096 |
| 29 | + ) # Read more data for potentially larger requests |
| 30 | + if not request_data: |
| 31 | + print(f"Client {addr} disconnected before sending data.") |
| 32 | + writer.close() |
| 33 | + await writer.wait_closed() |
| 34 | + return |
| 35 | + |
| 36 | + request_line = request_data.decode().splitlines()[0] |
| 37 | + print(f"Received request: {request_line}") |
| 38 | + |
| 39 | + response_body = "" |
| 40 | + status_code = 200 |
| 41 | + status_message = "OK" |
| 42 | + content_type = "text/plain" |
| 43 | + |
| 44 | + # For simplicity, we'll just check if it's a GET request |
| 45 | + if request_line.startswith("GET"): |
| 46 | + github_content = await fetch_url("https://github.com") |
| 47 | + |
| 48 | + # Truncate for brevity, as github.com's homepage can be very large |
| 49 | + display_content = github_content |
| 50 | + if len(github_content) > 1000: |
| 51 | + display_content = github_content[:1000] + "\n\n... (content truncated)" |
| 52 | + |
| 53 | + response_body = f"Hello from the Asyncio Server!\n\nFetched content from github.com:\n\n{display_content}" |
| 54 | + else: |
| 55 | + status_code = 405 |
| 56 | + status_message = "Method Not Allowed" |
| 57 | + response_body = "Only GET requests are supported." |
| 58 | + |
| 59 | + response = ( |
| 60 | + f"HTTP/1.1 {status_code} {status_message}\r\n" |
| 61 | + f"Content-Type: {content_type}\r\n" |
| 62 | + f"Content-Length: {len(response_body.encode('utf-8'))}\r\n" # Encode to get byte length |
| 63 | + f"\r\n" |
| 64 | + f"{response_body}" |
| 65 | + ) |
| 66 | + writer.write(response.encode("utf-8")) |
| 67 | + await writer.drain() |
| 68 | + |
| 69 | + except Exception as e: |
| 70 | + print(f"Error handling client {addr}: {e}", file=sys.stderr) |
| 71 | + # Attempt to send an error response if possible |
| 72 | + error_body = f"Internal Server Error: {e}" |
| 73 | + error_response = ( |
| 74 | + f"HTTP/1.1 500 Internal Server Error\r\n" |
| 75 | + f"Content-Type: text/plain\r\n" |
| 76 | + f"Content-Length: {len(error_body.encode('utf-8'))}\r\n" |
| 77 | + f"\r\n" |
| 78 | + f"{error_body}" |
| 79 | + ) |
| 80 | + writer.write(error_response.encode("utf-8")) |
| 81 | + await writer.drain() |
| 82 | + finally: |
| 83 | + print(f"Closing connection for {addr}") |
| 84 | + writer.close() |
| 85 | + await writer.wait_closed() |
| 86 | + |
| 87 | + |
| 88 | +async def main(): |
| 89 | + host = "127.0.0.1" |
| 90 | + port = 8080 |
| 91 | + |
| 92 | + server = await asyncio.start_server(handle_client, host, port) |
| 93 | + |
| 94 | + print(f"Serving on {host}:{port}") |
| 95 | + |
| 96 | + async with server: |
| 97 | + await server.serve_forever() |
| 98 | + |
| 99 | + |
| 100 | +if __name__ == "__main__": |
| 101 | + try: |
| 102 | + asyncio.run(main()) |
| 103 | + except KeyboardInterrupt: |
| 104 | + print("Server stopped by user.") |
| 105 | + except Exception as e: |
| 106 | + print(f"An unexpected error occurred in main: {e}", file=sys.stderr) |
| 107 | + sys.exit(1) |
0 commit comments