使用FastAPI搭建WebSocket服务,前端通过JavaScript连接,实现双向实时通信。后端用@app.websocket定义接口,管理连接列表并广播消息;前端创建WebSocket实例,监听onmessage事件接收数据,调用send发送消息。配合HTML页面和输入交互,完成简单聊天功能。注意处理异常、清理连接及心跳保活,确保稳定性。

要在Python网页版中实现WebSocket通信,核心是使用支持异步处理的后端框架配合前端JavaScript建立长连接。WebSocket能实现客户端与服务器之间的双向实时通信,非常适合聊天应用、实时数据推送等场景。下面从后端搭建、前端连接到完整示例,一步步说明如何开发。
选择合适的Python后端框架
Python中常用的WebSocket支持框架有以下几种:
- FastAPI + Uvicorn:基于ASGI的现代框架,原生支持WebSocket,开发效率高
- Sanic:异步Web框架,性能优秀,语法类似Flask
- Tornado:老牌异步框架,自带WebSocket模块,适合独立部署
推荐使用FastAPI,因其文档清晰、集成简单,且可直接通过@app.websocket装饰器定义接口。
使用FastAPI搭建WebSocket服务端
安装依赖:
立即学习“Python免费学习笔记(深入)”;
pip install fastapi uvicorn websockets
编写后端代码(main.py):
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
<p>app = FastAPI()</p><h1>存储所有活动连接</h1><p>active_connections = []</p><p>@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
active_connections.append(websocket)
try:
while True:
data = await websocket.receive_text()</p><h1>广播消息给所有连接</h1><pre class="brush:php;toolbar:false;"> for connection in active_connections:
if connection != websocket:
await connection.send_text(f"收到: {data}")
except:
active_connections.remove(websocket)</code>启动服务:
uvicorn main:app --reload
前端页面通过JavaScript连接WebSocket
创建一个简单的HTML页面,使用浏览器原生WebSocket API连接后端:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="message" placeholder="输入消息"/>
<button onclick="sendMessage()">发送</button>
<div id="output"></div>
<p><script>
const ws = new WebSocket("ws://127.0.0.1:8000/ws");</p><pre class="brush:php;toolbar:false;"><code>ws.onmessage = function(event) {
const output = document.getElementById("output");
const msg = document.createElement("p");
msg.textContent = event.data;
output.appendChild(msg);
};
function sendMessage() {
const input = document.getElementById("message");
ws.send(input.value);
input.value = "";
}










