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

Python中出现ConnectionResetError: [Errno 104] Connection reset by peer通常是因为对端服务器主动关闭了连接,而本地仍在尝试读取或写入数据。这类问题常见于网络请求、Socket通信或使用HTTP库(如requests)时。下面介绍几种常见的处理方式和预防措施。
该错误本质是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.1\r\nHost: example.com\r\n\r\n")
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}")
避免频繁创建新连接,复用连接减少异常概率:
以上就是Python连接重置错误ConnectionResetError处理方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号