python network_error ai_generated partial

WebSocket连接正常关闭:收到1000 (OK);然后发送1000 (OK)

websockets.exceptions.ConnectionClosedOK: received 1000 (OK); then sent 1000 (OK)

ID: python/starlette-websocket-disconnect

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

版本兼容性

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

根因分析

WebSocket连接被客户端或服务器正常关闭。

English

The WebSocket connection was closed by the client or server normally.

generic

解决方案

  1. 90% 成功率 Handle the close event gracefully and clean up resources.
    async def websocket_endpoint(websocket):
        await websocket.accept()
        try:
            while True:
                data = await websocket.receive_text()
                await websocket.send_text(f"Echo: {data}")
        except websockets.exceptions.ConnectionClosed:
            print('Connection closed')
  2. 85% 成功率 Implement reconnection logic with exponential backoff.
    import asyncio
    async def connect():
        while True:
            try:
                async with websockets.connect('ws://...') as ws:
                    await ws.send('hello')
            except websockets.exceptions.ConnectionClosed:
                await asyncio.sleep(1)

无效尝试

常见但无效的做法:

  1. Assuming it's an error and trying to reconnect indefinitely. 60% 失败

    Normal closure is not an error; reconnecting without reason is wasteful.

  2. Ignoring the close event and continuing to send messages. 90% 失败

    The connection is closed; sending messages will raise another error.