python network_error ai_generated true

aiohttp.client_exceptions.ServerDisconnectedError: 服务器断开连接

aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected

ID: python/aiohttp-serverdisconnectederror

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

版本兼容性

版本状态引入弃用备注
3.9+ active — — —

根因分析

远程服务器在发送完整 HTTP 响应之前关闭了 TCP 连接,通常由 keep-alive 超时、负载均衡器空闲限制或服务器崩溃引起。

English

The remote server closed the TCP connection before sending a complete HTTP response, often due to keep-alive timeouts, load balancer idle limits, or server-side crashes.

generic

解决方案

  1. 85% 成功率
    import aiohttp
    
    connector = aiohttp.TCPConnector(limit=100, enable_cleanup_closed=True)
    async with aiohttp.ClientSession(connector=connector) as s:
        for attempt in range(3):
            try:
                async with s.get(url) as r:
                    return await r.text()
            except aiohttp.ServerDisconnectedError:
                continue
  2. 80% 成功率
    connector = aiohttp.TCPConnector(keepalive_timeout=15)
    # plus exponential backoff wrapper around the request

无效尝试

常见但无效的做法:

  1. 75% 失败

    The disconnect is server-initiated, not a client timeout; longer timeouts just make failures slower.

  2. 60% 失败

    If the server closes mid-response, disabling keep-alive does not prevent the in-flight disconnect.