连接到 FastAPI 端点后 Websocket 立即关闭
我正在尝试将 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)
客户端
import aiohttp
import asyncio
async def main():
s = aiohttp.ClientSession()
ws = await s.ws_connect('ws://localhost:8000/ws')
while True:
...
asyncio.run(main())
当我尝试在建立连接时从服务器向客户端发送数据
服务器
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_text('yo')
客户端
while True:
print(await ws.receive())
I总是在我的客户端控制台中打印
WSMessage(type=<WSMsgType.CLOSED: 257>, data=None, extra=None)
而在服务器的调试控制台中它显示
INFO: ('127.0.0.1', 59792) - "WebSocket /ws" [accepted]
INFO: connection open
INFO: connection closed
当我尝试将数据从客户端发送到服务器
服务器
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
await websocket.receive_text()
客户端
ws = await s.ws_connect('ws://localhost:8000/ws')
await ws.send_str('client!')
什么也没有发生,我没有收到任何消息在服务器的控制台中打印出来,只是调试消息表明客户端已被接受,连接再次打开并关闭。
我不知道我做错了什么,我按照这个教程进行操作websocket 的 fastAPI 文档和 js websocket 的示例工作得很好。
I'm trying to connect a websocket aiohttp client to a fastapi websocket endpoint, but I can't send or recieve any data because it seems that the websocket gets closed immediately after connecting to the endpoint.
server
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)
client
import aiohttp
import asyncio
async def main():
s = aiohttp.ClientSession()
ws = await s.ws_connect('ws://localhost:8000/ws')
while True:
...
asyncio.run(main())
When I try to send data from the server to the client when a connection is made
server
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
await websocket.send_text('yo')
client
while True:
print(await ws.receive())
I always get printed in my client's console
WSMessage(type=<WSMsgType.CLOSED: 257>, data=None, extra=None)
While in the server's debug console it says
INFO: ('127.0.0.1', 59792) - "WebSocket /ws" [accepted]
INFO: connection open
INFO: connection closed
When I try to send data from the client to the server
server
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
await websocket.receive_text()
client
ws = await s.ws_connect('ws://localhost:8000/ws')
await ws.send_str('client!')
Nothing happens, I get no message printed out in the server's console, just the debug message saying the client got accepted, connection opened and closed again.
I have no idea what I'm doing wrong, I followed this tutorial in the fastAPI docs for a websocket and the example there with the js websocket works completely fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
连接由任一端(客户端或服务器)关闭,如代码片段所示。您需要在服务器和客户端中都有一个循环,以便能够连续等待消息以及发送消息(看看此处 和 此处)。
此外,根据 FastAPI 文档:
因此,在服务器端,您应该使用
try-except
块来捕获和处理WebSocketDisconnect
异常,以及websockets.exceptions.ConnectionClosed
例外情况,如此答案中所述。下面是一个工作示例,演示了使用websockets
进行客户端(在aiohttp
中)- 服务器(在FastAPI
中)通信。相关示例可以在此处和这里,以及此处和此处。工作示例
服务器
客户端
使用
websockets
库而不是aiohttp
的示例可以在此处,以及此处和此处。The connection is closed by either end (client or server), as shown from your code snippets. You would need to have a loop in both the server and the client for being able to
await
for messages, as well as send messages, continuously (have a look here and here).Additionally, as per FastAPI's documentation:
Thus, on server side, you should use a
try-except
block to catch and handleWebSocketDisconnect
exceptions, as well aswebsockets.exceptions.ConnectionClosed
exceptions, as explained in this answer. Below is a working example demonstrating a client (inaiohttp
) - server (inFastAPI
) communication usingwebsockets
. Related examples can be found here and here, as well as here and here.Working Example
Server
Client
Examples using the
websockets
library instead ofaiohttp
can be found here, as well as here and here.