Skip to content

Instantly share code, notes, and snippets.

@wybiral
Last active February 13, 2022 04:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wybiral/4cfc38ebf3fe3ee9eebeff9da7d60842 to your computer and use it in GitHub Desktop.
Save wybiral/4cfc38ebf3fe3ee9eebeff9da7d60842 to your computer and use it in GitHub Desktop.
import asyncio
# next client id
client = 1
async def handler(r, w):
line = await r.readline()
try:
method, path, version = line.split(b' ', 2)
except:
w.close()
return
# consume request
while True:
line = await r.readline()
if not line or line == b'\r\n':
break
# dispatch
if path == b'/':
await handle_index(r, w)
elif path == b'/theme.css':
await handle_theme(r, w)
w.close()
async def handle_index(r, w):
w.write(b'HTTP/1.1 200 OK\r\n')
w.write(b'Content-Type: text/html; charset=utf-8\r\n')
w.write(b'Link: <theme.css>; rel="prefetch", as="stylesheet"\r\n')
w.write(b'\r\n')
w.write(b'Hello world!')
await w.drain()
async def handle_theme(r, w):
global client
current = client
client += 1
w.write(b'HTTP/1.1 200 OK\r\n')
w.write(b'Content-Type: text/css\r\n')
w.write(b'\r\n')
print('connected client{}'.format(current))
# keep connection alive by slowly sending spaces
while True:
w.write(b' ')
try:
await w.drain()
except:
break
await asyncio.sleep(1)
print('disconnected client{}'.format(current))
async def main(host='127.0.0.1', port=8666):
s = await asyncio.start_server(handler, host, port)
print('Serving at http://{}:{}'.format(host, port))
await s.serve_forever()
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment