python runtime_error ai_generated true

RuntimeError: Cannot call 'receive' before 'accept' on a WebSocket

ID: python/starlette-websocket-accept-before-receive

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-08-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active

Root Cause

Starlette WebSocket 在未调用 accept 方法前尝试接收数据

generic

中文

Starlette WebSocket 在未调用 accept 方法前尝试接收数据

Workarounds

  1. 95% success 先调用 accept 再接收数据
    await websocket.accept()
    data = await websocket.receive_text()
  2. 90% success 在异步上下文管理器中处理
    async with websocket:
        await websocket.accept()
        async for message in websocket:
            ...

Dead Ends

Common approaches that don't work:

  1. 在 accept 前发送数据 90% fail

    同样需要先 accept

  2. 忽略 accept 直接使用 receive 95% fail

    WebSocket 连接未建立