-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncio_web_hello.py
37 lines (34 loc) · 1.02 KB
/
asyncio_web_hello.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import asyncio
async def dispatch(reader, writer):
while True:
data = await reader.readline()
message = data.decode()
writer.write(bytes(message, 'utf-8'))
# writer.writeline(message)
print(data)
if data == b'\r\n':
break
writer.writelines([
b'HTTP/1.0 200 OK\r\n',
b'Content-Type:text/html; charset=utf-8\r\n',
b'Connection: close\r\n',
b'\r\n',
b'<html><body>Hello World!<body></html>\r\n',
b'\r\n'
])
await writer.drain()
writer.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
coro = asyncio.start_server(dispatch, '127.0.0.1', 5555, 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()