无法在 FastAPI websocket 中从客户端获取数据 | Python

发布于 2025-01-09 15:14:47 字数 2197 浏览 1 评论 0原文

我在 fastapi 日志中收到此错误:

INFO:     ('172.28.0.1', 35088) - "WebSocket /ws" [accepted]
INFO:     connection open
ERROR:    Exception in ASGI application
...
    await self.app(scope, receive, send)
    File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 58, in __call__
    await self.app(scope, receive, send)
    File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
    await route.handle(scope, receive, send)
    File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 297, in handle
    await self.app(scope, receive, send)
    File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 68, in app
    await func(session)
    File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 273, in app
    await dependant.call(**values)
    File "/code/./app/main.py", line 127, in websocket_endpoint
    data = await websocket.receive_text()
     File "/usr/local/lib/python3.9/site-packages/starlette/websockets.py", line 85, in receive_text
     self._raise_on_disconnect(message)
    File "/usr/local/lib/python3.9/site-packages/starlette/websockets.py", line 80, in _raise_on_disconnect
    raise WebSocketDisconnect(message["code"])
    starlette.websockets.WebSocketDisconnect: 1000
    INFO:     connection closed

我找不到问题。为什么我的 fastapi 路由无法从客户端获取数据,但服务器向客户端发送的消息有效。

客户端代码:

import asyncio
from time import sleep
import websockets

async def get_work():
    async with websockets.connect("ws://localhost:3000/ws", open_timeout=None) as websocket:
        await websocket.send('Hello from CLient')
        answer = await websocket.recv()
        print(answer)
         
while True:
    asyncio.run(get_work())
    sleep(5)

服务器代码:

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        try:
            data = await websocket.receive_text()
            print(data)
        except RuntimeError:
            break
        await websocket.send_text("Hello from Server") 

非常感谢您的帮助!

I get this error in my fastapi log:

INFO:     ('172.28.0.1', 35088) - "WebSocket /ws" [accepted]
INFO:     connection open
ERROR:    Exception in ASGI application
...
    await self.app(scope, receive, send)
    File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 58, in __call__
    await self.app(scope, receive, send)
    File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
    await route.handle(scope, receive, send)
    File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 297, in handle
    await self.app(scope, receive, send)
    File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 68, in app
    await func(session)
    File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 273, in app
    await dependant.call(**values)
    File "/code/./app/main.py", line 127, in websocket_endpoint
    data = await websocket.receive_text()
     File "/usr/local/lib/python3.9/site-packages/starlette/websockets.py", line 85, in receive_text
     self._raise_on_disconnect(message)
    File "/usr/local/lib/python3.9/site-packages/starlette/websockets.py", line 80, in _raise_on_disconnect
    raise WebSocketDisconnect(message["code"])
    starlette.websockets.WebSocketDisconnect: 1000
    INFO:     connection closed

I can't find the problem. Why my fastapi route can't get the data from client but the server message to client works.

Client Code:

import asyncio
from time import sleep
import websockets

async def get_work():
    async with websockets.connect("ws://localhost:3000/ws", open_timeout=None) as websocket:
        await websocket.send('Hello from CLient')
        answer = await websocket.recv()
        print(answer)
         
while True:
    asyncio.run(get_work())
    sleep(5)

Server Code:

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        try:
            data = await websocket.receive_text()
            print(data)
        except RuntimeError:
            break
        await websocket.send_text("Hello from Server") 

Thanks a lot for help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文