Skip to content

Instantly share code, notes, and snippets.

@nitely
Last active December 18, 2015 23:17
Show Gist options
  • Save nitely/0f03b92c754f7aa73a3d to your computer and use it in GitHub Desktop.
Save nitely/0f03b92c754f7aa73a3d to your computer and use it in GitHub Desktop.
Python asyncio server (for benchmarking raw asyncio performance)
import asyncio
@asyncio.coroutine
def read_header(reader):
while True:
try:
data = yield from reader.readline()
except ConnectionResetError:
return
if reader.at_eof():
return
if data == b'\r\n':
return
@asyncio.coroutine
def echo_handler(reader, writer):
while True: # keep-alive
yield from read_header(reader)
if reader.at_eof(): # You can not write to the socket after this
break
writer.write(
b'HTTP/1.1 200 ok\r\n'
b'Content-Length: 0\r\n'
b'\r\n'
)
try:
yield from writer.drain()
except ConnectionResetError:
break
writer.close()
def runserver(handler, host='127.0.0.1', port=3000):
loop = asyncio.get_event_loop()
coro = asyncio.start_server(handler, host, port, loop=loop)
server = loop.run_until_complete(coro)
# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
if __name__ == "__main__":
runserver(echo_handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment