Skip to content

Instantly share code, notes, and snippets.

@iKalin
Forked from derekkwok/async-server.py
Created July 19, 2016 11:27
Show Gist options
  • Save iKalin/64b5d2d7bf7c73192dd4359cac4db067 to your computer and use it in GitHub Desktop.
Save iKalin/64b5d2d7bf7c73192dd4359cac4db067 to your computer and use it in GitHub Desktop.
Python 3.5 async "Hello World" server
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