python network_error ai_generated true

异步超时错误:WebSocket接收超时

asyncio.TimeoutError: WebSocket receive timed out

ID: python/starlette-websocket-timeout

其他格式: JSON · Markdown 中文 · English
80%修复率
81%置信度
0证据数
2024-08-15首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

WebSocket接收操作超过了配置的超时时间。

English

A WebSocket receive operation exceeds the configured timeout period.

generic

解决方案

  1. 90% 成功率 Use asyncio.wait_for with a reasonable timeout
    try:
        data = await asyncio.wait_for(websocket.receive_text(), timeout=10)
    except asyncio.TimeoutError:
        await websocket.close(code=1000)
  2. 85% 成功率 Set timeout in the WebSocket endpoint configuration
    from starlette.websockets import WebSocketEndpoint
    class MyEndpoint(WebSocketEndpoint):
        receive_timeout = 30

无效尝试

常见但无效的做法:

  1. Increasing timeout to an extremely high value 60% 失败

    May cause resource exhaustion; not a real fix.

  2. Ignoring the timeout and retrying indefinitely 85% 失败

    Leads to infinite loop and resource leak.