Chapter 13 · HTTP/2 and WebSocket
Chapter goals: Understand the advantages of HTTP/2 multiplexing, master httpx's HTTP/2 and WebSocket support.
13.1 HTTP/2 Multiplexing
HTTP/1.1 has head-of-line blocking issues - one slow request blocks all subsequent requests. HTTP/2 solves this through multiplexing:
bash
pip install "httpx[http2]"python
import httpx
# Enable HTTP/2
client = httpx.Client(h2=True)
resp = client.get('https://httpbin.org/get')
# Multiplexing: multiple requests share one TCP connection
with httpx.Client(h2=True) as client:
resp1 = client.get('https://api.github.com/users/octocat')
resp2 = client.get('https://api.github.com/users/torvalds')
# Two requests transmitted concurrently on the same connection, not blocking each other13.2 WebSocket Support
httpx has built-in WebSocket client:
python
import httpx
import asyncio
async def websocket_demo():
uri = "wss://echo.websocket.org"
async with httpx.AsyncClient() as client:
async with client.websocket_connect(uri) as ws:
await ws.send_text("Hello, WebSocket!")
response = await ws.receive_text()
print(f"Received: {response}") # Echo "Hello, WebSocket!"
asyncio.run(websocket_demo())13.3 Real-World Application Scenarios
python
import httpx
import asyncio
class RealtimeMonitor:
"""Real-time WebSocket data monitoring"""
def __init__(self, url: str):
self.url = url
self.client = httpx.AsyncClient()
async def connect(self):
self.ws = await self.client.websocket_connect(self.url)
await self.ws.send_text('subscribe: market_data')
async def listen(self):
async for message in self.ws.iter_text():
print(f"Received: {message}")
# Process real-time data...
async def close(self):
await self.ws.close()
await self.client.aclose()13.4 Chapter Summary
- HTTP/2 multiplexing improves concurrency performance, reducing connection count;
- httpx natively supports WebSocket without additional libraries;
- HTTP/2 requires extra installation:
pip install "httpx[http2]".
🧪 随堂测验
点击你认为正确的选项。答错时会展示正确答案与原因解析。
1. What is the core advantage of HTTP/2 over HTTP/1.1?
2. What is needed to enable HTTP/2 in httpx?
3. At which layer does httpx WebSocket client belong?
4. What scenarios is WebSocket suitable for?
🛠️ Hands-on Practice
- Compare HTTP/2 vs HTTP/1.1 concurrency performance with HTTP/2 enabled.
- Implement a WebSocket echo client, send 10 messages and verify echo.
- Create a real-time data subscriber that listens to WebSocket and processes messages.