我正在尝试将 websocket aiohttp 客户端连接到 fastapi websocket 端点,但我无法发送或接收任何数据,因为似乎 websocket 在连接到端点后立即关闭。
服务器
import uvicorn
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
...
if __name__ == '__main__':
uvicorn.run('test:app', debug=True, reload=True)
Run Code Online (Sandbox Code Playgroud)
客户
import aiohttp
import asyncio
async def main():
s = aiohttp.ClientSession()
ws = await s.ws_connect('ws://localhost:8000/ws')
while True:
...
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)
当我尝试在建立连接时将数据从服务器发送到客户端时
服务器
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_text('yo')
Run Code Online (Sandbox Code Playgroud)
客户
while True:
print(await ws.receive())
Run Code Online (Sandbox Code Playgroud)
我总是在客户的控制台中打印
WSMessage(type=<WSMsgType.CLOSED: 257>, data=None, extra=None)
Run Code Online (Sandbox Code Playgroud)
在服务器的调试控制台中它说
INFO: ('127.0.0.1', 59792) - …Run Code Online (Sandbox Code Playgroud)