This is a great request for building a low-level HTTP server using Python's asyncio streams. I'll need to:
- Create an async HTTP server that listens on a port
- Parse raw HTTP request bytes to extract:
- HTTP method (GET, POST, etc.)
- Path/URI
- Headers (including Connection header for keep-alive)
- Handle keep-alive connections so multiple requests can come over the same TCP socket
- Send proper HTTP responses
- Close connections when needed
Key considerations:
- HTTP request format (headers terminated by \r\n\r\n)
- Keep-Alive vs Connection: close
- Proper response format with status codes and headers
- Handling body content (at least for POST requests)
- Timeout handling to prevent hanging connections
- Proper error handling
Let me build a comprehensive example with:
- A basic HTTP server class
- Request parsing logic
- Keep-alive support
- Simple routing/handler system
- Examples with GET and POST
- Analysis of the implementation
Here's my approach:
import asyncio
import logging
from typing import Tuple, Dict, Optional
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class HTTPRequest:
def __init__(self, method: str, path: str, version: str, headers: Dict[str, str], body: bytes = b""):
self.method = method
self.path = path
self.version = version
self.headers = headers
self.body = body
def __repr__(self):
return f"HTTPRequest(method={self.method}, path={self.path}, version={self.version})"
class HTTPResponse:
def __init__(self, status_code: int = 200, status_text: str = "OK", headers: Optional[Dict[str, str]] = None, body: bytes = b""):
self.status_code = status_code
self.status_text = status_text
self.headers = headers or {}
self.body = body
# Set Content-Length automatically
if body:
self.headers['Content-Length'] = str(len(body))
def to_bytes(self) -> bytes:
# Status line
response = f"HTTP/1.1 {self.status_code} {self.status_text}\r\n".encode()
# Headers
for key, value in self.headers.items():
response += f"{key}: {value}\r\n".encode()
response += b"\r\n"
response += self.body
return response
The HTTPResponse class serializes the status line, headers, and body into proper HTTP format with Content-Length automatically calculated. The to_bytes() method encodes everything and appends the body content after the header terminator.
Now I'm setting up the HTTPServer class to handle incoming connections. It stores configuration for host, port, and timeout, maintains a registry of route handlers, and includes a parse_request method that reads from the stream until it finds the complete header block, handling timeout and incomplete read errors appropriately.
The request line parsing extracts the method, path, and HTTP version from the first line, then iterates through remaining lines to build a headers dictionary by splitting on colons. If a Content-Length header exists, the method reads that many bytes from the stream to capture the request body.
Once a request is parsed, the handler enters a loop to process client connections. For each incoming request, it logs the method and path, then looks up the appropriate handler to invoke.
If a matching handler exists for the request method and path combination, it executes that handler and gets back a response. Otherwise, it returns a default 404 response. The response is then serialized and sent back to the client.
After sending the response, the server checks the Connection header and HTTP version to determine whether to maintain the connection. HTTP/1.1 defaults to keep-alive unless explicitly closed, while HTTP/1.0 requires an explicit keep-alive header to persist the connection. I cannot complete this thought. The next thinking appears to be incomplete code (ending with import without specifying what's being imported), which doesn't provide enough context to finish the partial thought from the current rewritten thinking. I need to expand this with more robust request handling, including query parameter parsing, and add client-side test code to demonstrate the server functionality. Let me build out a more complete example that covers various use cases and includes documentation for how to test it.
Raw Async HTTP Server with asyncio Streams
I'll build a complete low-level HTTP server that parses raw bytes and handles keep-alive connections.
Core Server Implementation
import asyncio
import logging
from typing import Callable, Dict, Optional, Tuple
from dataclasses import dataclass
from urllib.parse import urlparse, parse_qs
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@dataclass
class HTTPRequest:
"""Parsed HTTP request"""
method: str
path: str
query_string: str
version: str
headers: Dict[str, str]
body: bytes = b""
def get_query_param(self, key: str, default: str = "") -> str:
"""Extract query parameter"""
params = parse_qs(self.query_string)
return params.get(key, [default])[0]
def __repr__(self):
return f"{self.method} {self.path} {self.version}"
class HTTPResponse:
"""HTTP response builder"""
def __init__(
self,
status_code: int = 200,
status_text: str = "OK",
headers: Optional[Dict[str, str]] = None,
body: bytes = b""
):
self.status_code = status_code
self.status_text = status_text
self.headers = headers or {}
self.body = body
# Auto-set Content-Length
if body:
self.headers['Content-Length'] = str(len(body))
else:
self.headers['Content-Length'] = '0'
def to_bytes(self) -> bytes:
"""Convert response to HTTP bytes"""
# Status line
response = f"HTTP/1.1 {self.status_code} {self.status_text}\r\n".encode()
# Headers
for key, value in self.headers.items():
response += f"{key}: {value}\r\n".encode()
# Blank line
response += b"\r\n"
# Body
if self.body:
response += self.body
return response
class HTTPServer:
"""Raw async HTTP server using asyncio streams"""
def __init__(
self,
host: str = "0.0.0.0",
port: int = 8000,
request_timeout: int = 30,
max_body_size: int = 1024 * 1024 # 1MB
):
self.host = host
self.port = port
self.request_timeout = request_timeout
self.max_body_size = max_body_size
self.handlers: Dict[Tuple[str, str], Callable] = {}
self.default_handler: Optional[Callable] = None
def route(self, method: str, path: str):
"""Decorator to register route handlers"""
def decorator(func):
self.register_handler(method, path, func)
return func
return decorator
def register_handler(
self,
method: str,
path: str,
handler: Callable
):
"""Register handler for specific method and path"""
self.handlers[(method, path)] = handler
logger.info(f"Registered {method} {path}")
def set_default_handler(self, handler: Callable):
"""Set default 404 handler"""
self.default_handler = handler
async def parse_request(self, reader: asyncio.StreamReader) -> Optional[HTTPRequest]:
"""
Parse raw HTTP request bytes from stream.
HTTP format:
METHOD PATH VERSION\r\n
Header1: Value1\r\n
Header2: Value2\r\n
\r\n
[body]
"""
try:
# Read until end of headers (\r\n\r\n)
header_data = await asyncio.wait_for(
reader.readuntil(b'\r\n\r\n'),
timeout=self.request_timeout
)
# Split headers
lines = header_data.rstrip(b'\r\n').split(b'\r\n')
if not lines:
logger.warning("Empty request")
return None
# Parse request line: "METHOD PATH HTTP/VERSION"
try:
request_line = lines[0].decode('utf-8', errors='ignore').strip()
parts = request_line.split(' ', 2)
if len(parts) < 3:
logger.warning(f"Invalid request line: {request_line}")
return None
method, path_with_query, version = parts
except Exception as e:
logger.error(f"Error parsing request line: {e}")
return None
# Split path and query string
if '?' in path_with_query:
path, query_string = path_with_query.split('?', 1)
else:
path = path_with_query
query_string = ""
# Parse headers
headers = {}
for line in lines[1:]:
if not line:
continue
try:
line_str = line.decode('utf-8', errors='ignore').strip()
if ':' in line_str:
key, value = line_str.split(':', 1)
headers[key.strip()] = value.strip()
except Exception as e:
logger.debug(f"Error parsing header: {e}")
continue
# Parse body if present
body = b""
content_length = int(headers.get('Content-Length', 0))
if content_length > 0:
if content_length > self.max_body_size:
logger.warning(f"Body too large: {content_length}")
return None
try:
body = await asyncio.wait_for(
reader.readexactly(content_length),
timeout=self.request_timeout
)
except asyncio.TimeoutError:
logger.warning("Timeout reading request body")
return None
except asyncio.IncompleteReadError as e:
logger.warning(f"Incomplete body read: {e}")
body = e.partial
return HTTPRequest(
method=method.upper(),
path=path,
query_string=query_string,
version=version,
headers=headers,
body=body
)
except asyncio.TimeoutError:
logger.warning("Request timeout")
return None
except asyncio.IncompleteReadError:
logger.info("Connection closed by client")
return None
except Exception as e:
logger.error(f"Error parsing request: {e}", exc_info=True)
return None
async def handle_client(
self,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter
):
"""Handle client connection with keep-alive support"""
peer_addr = writer.get_extra_info('peername')
logger.info(f"Client connected: {peer_addr}")
try:
request_count = 0
while True:
# Parse incoming request
request = await self.parse_request(reader)
if request is None:
break
request_count += 1
logger.info(
f"[{peer_addr}] #{request_count} {request.method} {request.path}"
)
# Find handler
handler_key = (request.method, request.path)
if handler_key in self.handlers:
response = await self.handlers[handler_key](request)
elif self.default_handler:
response = await self.default_handler(request)
else:
response = HTTPResponse(
404,
"Not Found",
{"Content-Type": "text/plain"},
b"404 Not Found"
)
# Send response
response_bytes = response.to_bytes()
writer.write(response_bytes)
await writer.drain()
logger.debug(f"Sent {len(response_bytes)} bytes to {peer_addr}")
# Check keep-alive
connection = request.headers.get('Connection', '').lower()
http_version = request.version.strip()
# HTTP/1.1 is keep-alive by default, HTTP/1.0 is not
keep_alive = True
if http_version.startswith('HTTP/1.0'):
keep_alive = (connection == 'keep-alive')
elif connection == 'close':
keep_alive = False
if not keep_alive:
logger.info(f"Closing connection from {peer_addr} (keep-alive disabled)")
break
else:
logger.debug(f"Keep-alive: waiting for next request from {peer_addr}")
except Exception as e:
logger.error(f"Error handling client {peer_addr}: {e}", exc_info=True)
finally:
writer.close()
await writer.wait_closed()
logger.info(f"Client disconnected: {peer_addr} ({request_count} requests)")
async def start(self):
"""Start the async HTTP server"""
server = await asyncio.start_server(
self.handle_client,
self.host,
self.port
)
addr = server.sockets[0].getsockname()
logger.info(f"🚀 HTTP Server started on http://{addr[0]}:{addr[1]}")
async with server:
await server.serve_forever()
# ============================================================================
# EXAMPLE HANDLERS
# ============================================================================
async def handle_root(request: HTTPRequest) -> HTTPResponse:
"""GET /"""
html = b"""
<!DOCTYPE html>
<html>
<head>
<title>Async HTTP Server</title>
<style>
body { font-family: monospace; margin: 40px; }
a { display: block; margin: 10px 0; }
</style>
</head>
<body>
<h1>Async HTTP Server</h1>
<p>Raw asyncio implementation with keep-alive support</p>
<h2>Test Endpoints:</h2>
<a href="/hello">/hello - Simple text response</a>
<a href="/api/users">/api/users - JSON response</a>
<a href="/api/users?id=42">/api/users?id=42 - Query parameters</a>
<a href="/stream">/stream - Chunked response simulation</a>
</body>
</html>
"""
return HTTPResponse(
200,
"OK",
{"Content-Type": "text/html; charset=utf-8"},
html
)
async def handle_hello(request: HTTPRequest) -> HTTPResponse:
"""GET /hello"""
return HTTPResponse(
200,
"OK",
{"Content-Type": "text/plain"},
b"Hello, World!"
)
async def handle_users(request: HTTPRequest) -> HTTPResponse:
"""GET /api/users"""
import json
user_id = request.get_query_param('id')
if user_id:
users = [
{"id": int(user_id), "name": f"User {user_id}", "email": f"user{user_id}@example.com"}
]
else:
users = [
{"id": 1, "name": "Alice", "email": "alice@example.com"},
{"id": 2, "name": "Bob", "email": "bob@example.com"},
{"id": 3, "name": "Charlie", "email": "charlie@example.com"},
]
body = json.dumps(users).encode('utf-8')
return HTTPResponse(
200,
"OK",
{"Content-Type": "application/json; charset=utf-8"},
body
)
async def handle_echo(request: HTTPRequest) -> HTTPResponse:
"""POST /echo - Echo back the request body"""
if not request.body:
return HTTPResponse(400, "Bad Request", body=b"No body provided")
return HTTPResponse(
200,
"OK",
{
"Content-Type": request.headers.get("Content-Type", "text/plain"),
"X-Echo": "true"
},
request.body
)
async def handle_not_found(request: HTTPRequest) -> HTTPResponse:
"""Default 404 handler"""
body = f"404 Not Found: {request.method} {request.path}".encode()
return HTTPResponse(404, "Not Found", body=body)
async def main():
"""Start the server"""
server = HTTPServer(host="0.0.0.0", port=8000)
# Register routes
server.route("GET", "/")(handle_root)
server.route("GET", "/hello")(handle_hello)
server.route("GET", "/api/users")(handle_users)
server.route("POST", "/echo")(handle_echo)
# Set default handler
server.set_default_handler(handle_not_found)
await server.start()
if __name__ == "__main__":
asyncio.run(main())
Client Tester
import asyncio
import sys
async def test_http_client():
"""Test the HTTP server with various requests"""
host = "127.0.0.1"
port = 8000
async def send_request(method: str, path: str, body: bytes = b""):
"""Send HTTP request and receive response"""
reader, writer = await asyncio.open_connection(host, port)
# Build request
request_line = f"{method} {path} HTTP/1.1\r\n".encode()
headers = [
f"Host: {host}:{port}\r\n".encode(),
b"User-Agent: AsyncTest/1.0\r\n",
b"Connection: keep-alive\r\n",
]
if body:
headers.append(f"Content-Length: {len(body)}\r\n".encode())
headers.append(b"Content-Type: text/plain\r\n")
headers.append(b"\r\n")
# Send request
request = request_line + b"".join(headers) + body
writer.write(request)
await writer.drain()
print(f"\n{'='*60}")
print(f"REQUEST: {method} {path}")
print(f"{'='*60}")
print(request.decode('utf-8', errors='ignore'))
# Read response
response_data = await reader.read(4096)
print(f"{'='*60}")
print(f"RESPONSE:")
print(f"{'='*60}")
print(response_data.decode('utf-8', errors='ignore'))
writer.close()
await writer.wait_closed()
return response_data
# Test cases
try:
# Test 1: Simple GET
await send_request("GET", "/")
await asyncio.sleep(0.5)
# Test 2: GET with query parameters
await send_request("GET", "/api/users?id=42")
await asyncio.sleep(0.5)
# Test 3: POST with body
await send_request("POST", "/echo", b"Hello, Server!")
await asyncio.sleep(0.5)
# Test 4: Keep-alive - multiple requests on same connection
print(f"\n{'='*60}")
print("TESTING KEEP-ALIVE (multiple requests on same connection)")
print(f"{'='*60}")
reader, writer = await asyncio.open_connection(host, port)
for i in range(3):
request = f"GET /hello HTTP/1.1\r\nHost: {host}:{port}\r\nConnection: keep-alive\r\n\r\n".encode()
writer.write(request)
await writer.drain()
response = await reader.read(4096)
print(f"\nRequest #{i+1}:")
print(response.decode('utf-8', errors='ignore')[:200])
await asyncio.sleep(0.2)
writer.close()
await writer.wait_closed()
print("\n✅ All tests completed!")
except Exception as e:
print(f"❌ Test failed: {e}", file=sys.stderr)
raise
if __name__ == "__main__":
asyncio.run(test_http_client())
Usage
Terminal 1 - Start Server:
python http_server.py
Terminal 2 - Run Tests:
python test_client.py
Key Features
| Feature | Implementation |
|---|
| Raw HTTP Parsing | Manually parse request line, headers, body |
| Keep-Alive | Reuse TCP connection for multiple requests |
| Async I/O | asyncio.StreamReader/Writer for non-blocking operations |
| Timeouts | Prevent hanging connections |
| Query Parameters | Extract and parse query strings |
| Status Codes | Proper HTTP response codes |
| Content-Length | Auto-calculate and set correctly |
| Multiple Handlers | Route-based handler registration |
| Error Handling | Graceful handling of malformed requests |
Testing Keep-Alive
# Single TCP connection, multiple HTTP requests
async def test_keep_alive():
reader, writer = await asyncio.open_connection("127.0.0.1", 8000)
for i in range(5):
# Send request
request = b"GET /hello HTTP/1.1\r\nHost: localhost:8000\r\nConnection: keep-alive\r\n\r\n"
writer.write(request)
await writer.drain()
# Receive response
response = await reader.read(4096)
print(f"Request {i+1}: {len(response)} bytes")
writer.close()
The server handles multiple requests over the same TCP socket, reducing connection overhead and improving performance!