我想在dictionary中存储和管理用户websocket连接,这样我就可以 for each 用户创建自定义事件.
Here's a really simple implementation of what I'm trying to achieve:个
from fastapi import FastAPI, WebSocket
app = FastAPI()
con = {}
@app.websocket("/ws/{id}")
async def websocket_endpoint(websocket: WebSocket, id: str):
try:
print("connect", id)
await websocket.accept()
con[id] = websocket
print("check", con.keys())
for uid in con:
print(uid)
await con[uid].send_text("hello")
except Exception as e:
print(e)
and here's the log :个
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [26605] using StatReload
INFO: Started server process [26610]
INFO: Waiting for application startup.
INFO: Application startup complete.
connect 1
INFO: ('127.0.0.1', 48346) - "WebSocket /ws/1" [accepted]
check dict_keys(['1'])
1
INFO: connection open
connect 2
INFO: ('127.0.0.1', 48354) - "WebSocket /ws/2" [accepted]
check dict_keys(['1', '2'])
1
Unexpected ASGI message 'websocket.send', after sending 'websocket.close'.
INFO: connection open
当我使用客户端1
连接到WebSocket时,一切都按预期进行,我收到消息hello
.
client 1 log:个
CONNECTING: WS://LOCALHOST:8000/WS/1
CONNECTION READY
hello
CONNECTION CLOSED!
但是,当秒客户端连接到websocket
时,它会在服务器中返回一个异常:
Unexpected ASGI message 'websocket.send', after sending 'websocket.close'.
and client 2 doesn't get any message:个
CONNECTING: WS://LOCALHOST:8000/WS/1
CONNECTION READY
CONNECTION CLOSED!
I run the app like this:个
uvicorn main:app --reload
我到底做错了什么?