python network_error ai_generated partial

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

ID: python/starlette-websocket-disconnect

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-09-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

  1. 90% success 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% success 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)

Dead Ends

Common approaches that don't work:

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

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

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

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