-
-
Save iKalin/64b5d2d7bf7c73192dd4359cac4db067 to your computer and use it in GitHub Desktop.
Python 3.5 async "Hello World" server
This file contains 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 | |
import socket | |
SERVER_ADDRESS = (HOST, PORT) = '', 8888 | |
REQUEST_QUEUE_SIZE = 5 | |
http_response = b"""\ | |
HTTP/1.1 200 OK | |
Hello, World! | |
""" | |
q = asyncio.Queue() | |
async def produce(): | |
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
listen_socket.bind(SERVER_ADDRESS) | |
listen_socket.listen(REQUEST_QUEUE_SIZE) | |
listen_socket.setblocking(0) | |
print('Serving HTTP on port {port} ...'.format(port=PORT)) | |
loop = asyncio.get_event_loop() | |
while True: | |
client_connection, client_address = await loop.sock_accept(listen_socket) | |
await q.put((client_connection, client_address)) | |
async def consume(): | |
while True: | |
client_connection, client_address = await q.get() | |
request = client_connection.recv(1024) | |
print('-' * 80) | |
print(request.decode()) | |
client_connection.sendall(http_response) | |
client_connection.close() | |
loop = asyncio.get_event_loop() | |
loop.create_task(produce()) | |
loop.create_task(consume()) | |
loop.run_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment