Python3.7在Windows下出现ConnectionAbortedError: [WinError 10053]错误如何解决?

server 代码

# coding: utf-8
import socketserver

class Handler_TCPServer(socketserver.BaseRequestHandler): “”" The TCP Server class for demonstration.

Note: We need to implement the Handle method to exchange data
with TCP client.

"""

def handle(self):
    # self.request - TCP socket connected to the client
    self.data = self.request.recv(1024).strip()
    print("{} sent:".format(self.client_address[0]))
    print(self.data)
    # just send back ACK for data arrival confirmation
    self.request.sendall("ACK from TCP Server".encode())

if name == “main”: HOST, PORT = “0.0.0.0”, 8305

# Init the TCP server object, bind it to the localhost on 9999 port
tcp_server = socketserver.TCPServer((HOST, PORT), Handler_TCPServer)

# Activate the TCP server.
# To abort the TCP server, press Ctrl-C.
tcp_server.serve_forever()

client 代码:

# coding: utf-8
import socket
from multiprocessing import Process

def craw(index): host_ip, server_port = “localhost”, 8305 data = “Hello how are you?\n”

# Initialize a TCP client socket using SOCK_STREAM
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_client.connect((host_ip, server_port))
for i in range(100):
    # try:
    # Establish connection to TCP server and exchange data
    data = "process:{},index:{},".format(index, i) + data
    tcp_client.sendall(data.encode())

    # Read data from the TCP server and close the connection
    received = tcp_client.recv(1024)
    # finally:
    # tcp_client.close()

    print("process:{},index:{},Bytes Sent:     {}".format(index, i, data))
    print("process:{},index:{} Bytes Received: {}".format(index, i, received.decode()))

if name == ‘main’: p1 = Process(target=craw, args=(1,)) p2 = Process(target=craw, args=(2,)) p1.start() p2.start() p1.join() p2.join() print(“Complete”)

错误

Traceback (most recent call last):
  File "C:\Python37\lib\multiprocessing\process.py", line 297, in _bootstrap
    self.run()
  File "C:\Python37\lib\multiprocessing\process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "F:\Seafile\Nutstore\pycode2\learnqt\tcpcode\tcp_client.py", line 20, in craw
    received = tcp_client.recv(1024)
ConnectionAbortedError: [WinError 10053] 你的主机中的软件中止了一个已建立的连接。

这是什么问题?我使用多进程 socket 的方式有问题?或者应该怎么使用呢?


Python3.7在Windows下出现ConnectionAbortedError: [WinError 10053]错误如何解决?

1 回复

这个错误通常是因为连接被本地主机上的软件(比如防火墙、杀毒软件)或远程主机主动终止了。在Windows上,10053错误(WSAECONNABORTED)意味着已建立的连接被你的机器上的软件中止了。

最常见的原因和解决方法如下:

  1. 检查防火墙和杀毒软件:这是首要怀疑对象。暂时禁用它们(或为你的Python程序添加例外规则)测试一下。
  2. 调整socket超时和缓冲区:远程服务器或你的程序可能因为处理慢而断开连接。可以尝试设置更大的超时和缓冲区。
  3. 使用更稳健的连接方式:对于HTTP请求,使用requests库并启用重试机制是更好的选择。

涉及代码的解决方案示例:

如果你在使用低层级的socket

import socket

# 创建socket时设置超时
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.settimeout(30.0)  # 设置超时时间,例如30秒

try:
    client_socket.connect(('hostname', port))
    # ... 进行数据收发操作
except socket.timeout:
    print("连接超时")
except ConnectionAbortedError as e:
    print(f"连接被中止: {e}")
finally:
    client_socket.close()

如果你在使用requests库(推荐):

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# 配置重试策略
retry_strategy = Retry(
    total=3,  # 总重试次数
    backoff_factor=1,  # 退避因子
    status_forcelist=[429, 500, 502, 503, 504],  # 遇到这些状态码会重试
    allowed_methods=["GET", "POST"]  # 只对这些方法重试
)

# 创建带重试的会话
adapter = HTTPAdapter(max_retries=retry_strategy)
session = requests.Session()
session.mount("http://", adapter)
session.mount("https://", adapter)

try:
    response = session.get('http://example.com', timeout=10)
    print(response.text)
except requests.exceptions.ConnectionError as e:
    print(f"连接错误: {e}")

总结建议:优先使用requests库并配置重试和超时来处理网络连接。

回到顶部