You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.5 WebSocket流处理遇WebSocketConnectionClosedException求处理方案

Fixing WebSocketConnectionClosedException When Restarting Streamed Connections

I’ve run into this exact WebSocket disconnect issue countless times—your core idea of catching the exception and restarting the connection is on the right track, but there are a few key details you might be missing to make the restart logic robust and reliable.

First, let’s recap the error you’re seeing:

raise WebSocketConnectionClosedException("socket is already closed.")
websocket._exceptions.WebSocketConnectionClosedException: socket is already closed.

This error pops up when your code tries to use a WebSocket object that’s already been terminated (either by the remote server, a network drop, or timeout), but your script hasn’t yet switched to a fresh connection.

Looking at your current exception handler:

except WebSocketConnectionClosedException as e:
    ws = opensocket()
    websocket_open = True
    data = "WebSocketConnectionClosedException trying to restart stream"
    send_email(data,recipient)
    print(e)

Here are my suggestions to improve this:

  • Clean up the old connection first
    Before creating a new connection, always ensure the old one is properly closed to avoid resource leaks. Even if it’s already closed, calling close() won’t cause issues:

    except WebSocketConnectionClosedException as e:
        # Clean up stale connection
        if 'ws' in locals() or 'ws' in globals():
            try:
                ws.close()
            except Exception:
                pass  # Ignore any errors during close—connection is already dead
        # Create new connection
        ws = opensocket()
        websocket_open = True
        # Update notification to confirm restart
        data = "WebSocketConnectionClosedException: Stream restarted successfully"
        send_email(data, recipient)
        print(f"Reconnected after error: {e}")
    
  • Add reconnection retries
    Network blips can make the first restart attempt fail. Adding a retry loop with delays will make your script more resilient:

    import time
    
    except WebSocketConnectionClosedException as e:
        max_retries = 3
        retry_count = 0
        success = False
        
        while retry_count < max_retries:
            try:
                # Clean up old connection first
                if 'ws' in locals() or 'ws' in globals():
                    try:
                        ws.close()
                    except Exception:
                        pass
                # Attempt new connection
                ws = opensocket()
                websocket_open = True
                success = True
                break
            except Exception as retry_err:
                retry_count += 1
                print(f"Retry {retry_count}/{max_retries} failed: {retry_err}")
                time.sleep(2)  # Wait 2 seconds before retrying
        
        if success:
            data = "WebSocketConnectionClosedException: Stream restarted successfully after retries"
            send_email(data, recipient)
            print(f"Reconnected after error: {e}")
        else:
            data = "WebSocket reconnection failed after 3 attempts—stream is down"
            send_email(data, recipient)
            # You might want to trigger an alert or exit gracefully here
    
  • Validate your opensocket() function
    Double-check that opensocket() is creating a brand-new, valid WebSocket connection every time it’s called. It should be calling something like websocket.create_connection() (or your library’s equivalent) from scratch, not returning a cached or previously failed connection instance.

  • Add pre-checks for connection health
    To catch dead connections before they throw exceptions, add a quick health check in your main processing loop:

    def is_websocket_alive(ws):
        try:
            # Send a ping frame to verify connection
            ws.ping()
            return True
        except Exception:
            return False
    
    # In your main loop
    while websocket_open:
        if not is_websocket_alive(ws):
            # Force a reconnection by raising the exception
            raise WebSocketConnectionClosedException("Connection lost during processing")
        # Proceed with receiving/sending data
    

Your initial handler is a solid starting point—focusing on cleaning up stale connections, adding retries, and validating new connections will make your stream handling much more stable.

内容的提问来源于stack exchange,提问作者Beatrix Kidco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:05:11