Python如何实现WebSocket通信?
中等Python
答题要点
# websockets库(客户端)
import asyncio
import websockets
async def websocket_client():
uri = 'wss://stream.example.com/data'
async with websockets.connect(uri) as ws:
# 发送消息
await ws.send('{"action": "subscribe", "channel": "prices"}')
# 接收消息
async for message in ws:
data = json.loads(message)
process_data(data)
# 带重连的客户端
async def robust_client():
while True:
try:
async with websockets.connect(uri) as ws:
async for message in ws:
process_data(message)
except websockets.ConnectionClosed:
print("Connection lost, reconnecting...")
await asyncio.sleep(5)
# FastAPI WebSocket服务端
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
class ConnectionManager:
def __init__(self):
self.active_connections: list[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
manager = ConnectionManager()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.broadcast(f"Message: {data}")
except WebSocketDisconnect:
manager.active_connections.remove(websocket)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题