杰瑞科技汇

Python中errno 10054错误如何解决?

Of course. Let's break down errno 10054 in Python. This is a very common error, especially for network programmers.

Python中errno 10054错误如何解决?-图1
(图片来源网络,侵删)

The Short Answer

errno 10054 (WSAECONNRESET on Windows) means "Connection reset by peer."

In simple terms, the other side of your network connection abruptly closed it. Think of it like hanging up the phone in the middle of a conversation. Your program was trying to send or receive data, but the socket was suddenly terminated.


Detailed Explanation

What is "Connection reset by peer"?

The term "peer" just means the other computer or application you are connected to. The error message is slightly misleading because it implies the peer reset the connection, but the underlying system call on your machine reports it this way.

The connection was closed in a way that was not graceful. A graceful close involves both sides agreeing to end the conversation (e.g., one side sends a "FIN" packet, the other acknowledges it). A "reset" is an abrupt, forceful closure.

Python中errno 10054错误如何解决?-图2
(图片来源网络,侵删)

What Happens at the Network Level?

This is almost always caused by the peer sending a TCP RST (Reset) packet. This packet is a clear signal to your operating system: "Stop all communication on this connection immediately. Discard any data you were about to send."

Your Python program, unaware of the RST packet, tries to use the socket. When it does, the OS informs the program that the connection is no longer valid, resulting in the 10054 error.


Common Causes (Why does this happen?)

Understanding the why is key to debugging. The cause almost always lies with the peer (the server or client you're connected to), not your Python code itself.

Cause Description Analogy
Server Crash/Restart The application on the server side crashed, was killed, or was restarted. When it restarts, it doesn't know about your old connection and sends an RST to clean up stale connections. You're talking to a call center agent, and their computer suddenly bluescreens. The line goes dead.
Server Timeouts The server has a policy to drop idle connections. If your connection was inactive for too long, the server might have closed its end and sent an RST when you tried to use it again. You leave a web page open for an hour. When you try to click a link, the session has expired and you're logged out.
Firewall/Proxy Intervention A firewall or proxy between you and the peer might be blocking the traffic or timing out the connection. It can send an RST packet to terminate the connection. A bouncer at a club (the firewall) sees you talking to someone inside for too long and cuts the conversation short.
Application Logic Error The peer's application code has a bug. For example, it might be processing your request, encounters an error, and instead of sending a proper error message (like an HTTP 500), it just closes the socket. You ask a question, the person you're talking to gets confused and just walks away without saying goodbye.
Port Conflict The peer application might have bound to the same port your Python program is trying to connect to, forcing your connection to be rejected. You try to call a friend, but they've given their phone number to someone else, who now answers and hangs up on you.

How to Handle It in Python (Code Examples)

You can't prevent the peer from resetting the connection, but you can make your code robust enough to handle the error gracefully.

Python中errno 10054错误如何解决?-图3
(图片来源网络,侵删)

Detecting the Error

The error is raised as a socket exception. You should always wrap network operations in a try...except block.

import socket
import errno
HOST = 'example.com'
PORT = 80
try:
    # Create a socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.settimeout(5) # Set a timeout
        s.connect((HOST, PORT))
        s.sendall(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')
        # This is where the error will likely occur
        data = s.recv(1024)
    print(f"Received: {data.decode('utf-8')}")
except socket.error as e:
    # Check if the error is a connection reset
    if e.errno == errno.WSAECONNRESET: # On Windows
        print("Error: Connection was reset by the peer.")
    elif e.errno == errno.ECONNRESET: # On Linux/macOS
        print("Error: Connection was reset by the peer.")
    else:
        print(f"A socket error occurred: {e}")
except socket.timeout:
    print("Error: The connection timed out.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Note: The specific errno constant can be platform-dependent.

  • Windows: errno.WSAECONNRESET (value 10054)
  • Linux/macOS: errno.ECONNRESET (value 104)

A more cross-platform way is to compare the integer value directly:

except socket.error as e:
    if e.errno == 10054 or e.errno == 104: # Windows or Linux
        print("Error: Connection was reset by the peer.")

Best Practices to Mitigate the Problem

While you can't stop the reset, you can make your application more resilient.

  • Implement Retries with Exponential Backoff: If the error occurs, it might be a temporary issue (e.g., a server glitch). Don't give up immediately. Wait a bit and try again.

    import time
    import random
    def resilient_request(url, max_retries=3):
        for attempt in range(max_retries):
            try:
                # ... (your socket connection code here) ...
                return data # Success!
            except socket.error as e:
                if e.errno in [10054, 104]: # Connection Reset
                    if attempt < max_retries - 1:
                        wait_time = (2 ** attempt) + random.uniform(0, 1)
                        print(f"Connection reset. Retrying in {wait_time:.2f} seconds... (Attempt {attempt + 1})")
                        time.sleep(wait_time)
                        continue
                    else:
                        print("Max retries reached. Giving up.")
                        raise
                else:
                    # It's a different error, so re-raise it
                    raise
  • Use Higher-Level Libraries: Instead of raw sockets, use libraries like requests for HTTP or aiosocket for async operations. These libraries handle many low-level errors for you, including automatically retrying certain requests.

  • Set Timeouts: Always set a timeout on your sockets (socket.settimeout()). This prevents your program from hanging indefinitely if the peer goes silent. It will raise a socket.timeout exception, which is easier to handle than a generic 10054 that might occur after a long wait.

  • Check Logs: If you control the peer, check its server/application logs. The logs will almost certainly contain clues about why it reset the connection (e.g., a crash, an error, a restart).

分享:
扫描分享到社交APP
上一篇
下一篇