不知道什么时候FastApi官网更新了websockets页面
1.打开以下网页直接拖到最后复制官网代码
https://fastapi.tiangolo.com/advanced/websockets/
复制
回看一下FastApi
我现在复制并创建了一个名为main.py
的文件,内容如下
顺便加了些备注
# from typing import List
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<h2>Your ID: <span id="ws-id"></span></h2>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
// 生成id
var client_id = Date.now()
document.querySelector("#ws-id").textContent = client_id;
var ws = new WebSocket(`ws://localhost:8000/ws/${client_id}`);
// 页面显示发送内容
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
// 点击onsubmit调用函数sendMessage
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
class ConnectionManager:
def __init__(self):
# 定义类属性 有效连接 储存WebSocket对象
self.active_connections: List[WebSocket] = []
# 创建连接
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
# 删除websocket连接
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
# 发送个人消息
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
# 广播
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
# 创建一个名为manager的对象
manager = ConnectionManager()
# 页面请求
@app.get("/")
async def get():
# 返回http页面
return HTMLResponse(html)
# websocket请求
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
# 使用connect方法
await manager.connect(websocket)
try:
while True:
# 连接关闭时await websocket.receive_text()将引发WebSocketDisconnect异常
data = await websocket.receive_text()
# 调用发送个人信息send_personal_message方法
await manager.send_personal_message(f"You wrote: {data}", websocket)
# 调用广播broadcast方法
await manager.broadcast(f"Client #{client_id} says: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"Client #{client_id} left the chat")
启动
直接启动服务
uvicorn main:app --reload
回看
官网的教程也是定义了一个类
class ConnectionManager:
创建了一个类属性来存储websocket对象,比我之前写的好多了(用了一个字典来存)当时是完全不知道websocket对象的操作方法,一点也不优雅
self.active_connections: List[WebSocket] = []
类方法有以下4个
连接
async def connect(self, websocket: WebSocket):
发送个人消息,仅自己可见
async def send_personal_message(self, message: str, websocket: WebSocket):
广播
async def broadcast(self, message: str):
删除socket连接(这里为什么不用 async)
def disconnect(self, websocket: WebSocket):
以下内容为前端展示
==================================================================
用户标识用前端来展示,很方便也不用考虑那么多
var client_id = Date.now()
document.querySelector("#ws-id").textContent = client_id;
发送请求的函数 ”vent对象(没搞懂)”
function sendMessage(event)
看了官网的再看自己的,感觉之前好多地方之前都没考虑到
还是官网的代码好用,所以我为什么要自己敲