Simple TCP server that echo everything with prepended HTTP response headers.
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
#!/usr/bin/env python3 | |
import asyncio | |
from asyncio import StreamReader, StreamWriter | |
LISTEN = ('::', 8080) | |
WAIT_SECS = 3 | |
BUF_SIZE = 4096 | |
HTTP_RESPONSE = [ | |
'HTTP/1.1 200 OK', | |
'Server: http_echo', | |
'Connection: Closed', | |
'Content-Type: text/plain' | |
] | |
async def handle_client(reader: StreamReader, writer: StreamWriter): | |
peer = writer.get_extra_info('peername') | |
print(f'Accept {peer}') | |
head = '\r\n'.join(HTTP_RESPONSE) + '\r\n\r\n' | |
writer.write(head.encode()) | |
await writer.drain() | |
try: | |
while not reader.at_eof(): | |
data = await asyncio.wait_for(reader.read(BUF_SIZE), WAIT_SECS) | |
if data: | |
writer.write(data) | |
await writer.drain() | |
except TimeoutError: | |
pass | |
writer.write_eof() | |
writer.close() | |
await writer.wait_closed() | |
async def main(): | |
server = await asyncio.start_server(handle_client, *LISTEN) | |
addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets) | |
print(f'Listen on {addrs}') | |
async with server: | |
await server.serve_forever() | |
if __name__ == '__main__': | |
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