ConnectionResetError通常因对端关闭连接导致,需通过异常捕获、重试机制和连接复用优化处理。

python中出现ConnectionResetError: [errno 104] connection reset by peer通常是因为对端服务器主动关闭了连接,而本地仍在尝试读取或写入数据。这类问题常见于网络请求、Socket通信或使用http库(如requests)时。下面介绍几种常见的处理方式和预防措施。
理解ConnectionResetError原因
该错误本质是TCP连接被对方强制关闭。可能的原因包括:
捕获并处理异常
最直接的方法是在可能发生网络IO的地方使用try-except捕获异常:
import requests from requests.exceptions import ConnectionError try: response = requests.get("https://example.com", timeout=10) print(response.text) except ConnectionError as e: print(f"连接错误: {e}") except Exception as e: print(f"其他错误: {e}")
对于底层socket操作:
立即学习“Python免费学习笔记(深入)”;
import socket try: sock = socket.socket() sock.connect(('example.com', 80)) sock.send(b"GET / HTTP/1.1rnHost: example.comrnrn") data = sock.recv(1024) except ConnectionResetError: print("连接被对端重置") finally: sock.close()
添加重试机制
对于临时性网络抖动,自动重试可以提升程序稳定性:
from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry import requests Session = requests.Session() retries = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504]) session.mount('http://', HTTPAdapter(max_retries=retries)) session.mount('https://', HTTPAdapter(max_retries=retries)) try: response = session.get("http://example.com", timeout=5) except requests.exceptions.RequestException as e: print(f"请求失败: {e}")
优化连接管理
避免频繁创建新连接,复用连接减少异常概率:
基本上就这些。关键是根据具体场景选择合适的处理策略,结合异常捕获、重试机制和连接优化,能显著降低ConnectionResetError的影响。


