Providing raw asyncio HTTP server example
Here's Python code for an async HTTP server using asyncio streams that parses raw HTTP requests, supports keep-alive per HTTP/1.0 and HTTP/1.1 semantics, reads headers and optional body, and handles multiple requests per connection without frameworks.
Below is a minimal example of a raw HTTP/1.x server built on asyncio streams, without using Flask/FastAPI. It parses the request line and headers from the raw bytes, reads the body if Content-Length is present, and keeps the connection open for multiple requests on the same socket unless the client sends Connection: close (or we decide to close it).
import asyncio
from typing import Dict, Tuple, Optional
CRLF = b"\r\n"
async def read_headers(reader: asyncio.StreamReader, max_size: int = 16 * 1024) -> bytes:
"""
Read bytes from the stream until the end-of-headers marker (b"\r\n\r\n").
Returns the raw header bytes (including the final CRLFCRLF). If connection
closes before headers complete, returns b"".
"""
data = b""
while True:
chunk = await reader.read(1024)
if not chunk:
# Connection closed
return b""
data += chunk
if len(data) > max_size:
raise ValueError("Header section too large")
# End of headers
if b"\r\n\r\n" in data:
break
return data
def parse_request(raw: bytes) -> Tuple[str, str, str, Dict[str, str], bytes]:
"""
Parse the raw HTTP request up to (and including) the CRLFCRLF sequence.
Returns (method, path, version, headers, leftover), where 'leftover' is
any unread bytes after the headers (part of the body if the client already
pipelined data).
"""
head, sep, leftover = raw.partition(b"\r\n\r\n")
lines = head.decode("iso-8859-1").split("\r\n")
request_line = lines[0]
parts = request_line.split(" ")
if len(parts) != 3:
raise ValueError(f"Malformed request line: {request_line}")
method, path, version = parts
headers: Dict[str, str] = {}
for line in lines[1:]:
if not line:
continue
# Simple split on first colon
if ":" not in line:
continue
name, val = line.split(":", 1)
headers[name.strip().lower()] = val.strip()
return method, path, version, headers, leftover
async def read_body(reader: asyncio.StreamReader, headers: Dict[str, str], leftover: bytes) -> bytes:
"""
Read the body based on 'Content-Length'. Any bytes already read that belong
to the body are passed in via 'leftover'.
"""
content_length = headers.get("content-length")
if not content_length:
return b"" # No body
try:
length = int(content_length)
except ValueError:
raise ValueError("Invalid Content-Length")
already = leftover[:length]
remaining = length - len(already)
if remaining > 0:
tail = await reader.readexactly(remaining)
body = already + tail
else:
body = already[:length]
return body
def should_keep_alive(version: str, headers: Dict[str, str]) -> bool:
"""
For HTTP/1.1 default is keep-alive unless Connection: close is sent.
For HTTP/1.0 default is close unless Connection: keep-alive is sent.
"""
conn_val = headers.get("connection", "").lower()
if version == "HTTP/1.1":
return conn_val != "close"
elif version == "HTTP/1.0":
return conn_val == "keep-alive"
# Fallback
return False
def build_response(body: bytes, status: str = "200 OK", keep_alive: bool = True) -> bytes:
lines = [
f"HTTP/1.1 {status}",
f"Content-Length: {len(body)}",
"Content-Type: text/plain; charset=utf-8",
"Connection: keep-alive" if keep_alive else "Connection: close",
"",
""
]
header_block = "\r\n".join(lines).encode("iso-8859-1")
return header_block + body
async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
peer = writer.get_extra_info("peername")
print(f"Client connected: {peer}")
try:
while True:
# Read raw headers
raw_headers = await read_headers(reader)
if not raw_headers:
# Client closed connection
break
# Parse request
try:
method, path, version, headers, leftover = parse_request(raw_headers)
except ValueError as e:
print(f"Error parsing request: {e}")
# Send 400 and close
resp = build_response(b"Bad Request", status="400 Bad Request", keep_alive=False)
writer.write(resp)
await writer.drain()
break
# Read body if necessary (Content-Length only)
try:
body = await read_body(reader, headers, leftover)
except Exception as e:
print(f"Error reading body: {e}")
resp = build_response(b"Bad Request", status="400 Bad Request", keep_alive=False)
writer.write(resp)
await writer.drain()
break
# For demonstration, just echo back some info:
response_body = (
f"Hello from async server!\n"
f"Method: {method}\n"
f"Path: {path}\n"
f"HTTP Version: {version}\n"
f"Headers: {headers}\n"
f"Body: {body.decode(errors='ignore')}\n"
).encode("utf-8")
keep_alive = should_keep_alive(version, headers)
resp = build_response(response_body, keep_alive=keep_alive)
writer.write(resp)
await writer.drain()
if not keep_alive:
break
except asyncio.IncompleteReadError:
# Client closed abruptly
pass
except Exception as e:
print(f"Unexpected error: {e}")
finally:
writer.close()
await writer.wait_closed()
print(f"Client disconnected: {peer}")
async def main(host="127.0.0.1", port=8080):
server = await asyncio.start_server(handle_client, host, port)
addr = ", ".join(str(sock.getsockname()) for sock in server.sockets)
print(f"Serving on {addr}")
async with server:
await server.serve_forever()
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
How it works
read_headers reads until it encounters \r\n\r\n, marking the end of the HTTP header section.
parse_request parses the request line (METHOD PATH VERSION) and collects headers into a dict.
read_body reads the body if a Content-Length header is present. If the client has already sent part of the body in the same TCP frame (pipelined), it consumes those bytes first.
should_keep_alive determines whether to keep the connection open based on the HTTP version and the Connection header.
- The server then responds with a simple plaintext message and either leaves the connection open (for additional requests) or closes it.
Testing
You can test it with:
curl -v http://127.0.0.1:8080/hello
curl -v -d "data=123" http://127.0.0.1:8080/
Multiple requests on the same connection will work if curl sends Connection: keep-alive (HTTP/1.1 is keep-alive by default).