杰瑞科技汇

python socket 10061

Of course. Let's break down what Python socket error 10061 means, why it happens, and how to fix it.

python socket 10061-图1
(图片来源网络,侵删)

The Short Answer: What is Error 10061?

In Python, when you're using the socket module, error: [Errno 10061] Connection refused is a specific error code.

It means: A client actively tried to connect to a server, but the server program was not running or not listening on the specified address and port.

Think of it like this: You (the client) are calling a friend's phone (the server IP and port). The phone system (the network) can reach your friend's number, but your friend's phone is either turned off or not ringing. The connection is actively and explicitly rejected.


The Detailed Breakdown: The OSI Model Perspective

To understand why this happens, it's helpful to know what the operating system does when a connection request arrives:

python socket 10061-图2
(图片来源网络,侵删)
  1. Client Request: Your Python client code does socket.connect(('SERVER_IP', PORT)).
  2. OS Handshake: The client's operating system sends a SYN (Synchronize) packet to the server's IP and port.
  3. Server's Response: The server's operating system receives the SYN packet.
    • If a server is LISTENING on that port: The OS responds with a SYN-ACK (Synchronize-Acknowledge), and the connection process (TCP handshake) continues.
    • If NO server is listening on that port: The OS has nothing to do with this packet. It doesn't belong to any application. The OS responds with a RST (Reset) packet. This is the "Connection refused."
    • If a firewall is blocking the port: The firewall might simply drop the packet, which could lead to a "timeout" error instead of a "Connection refused." However, some firewalls are configured to explicitly send a RST.

In summary, 10061 is the error code you get when the server's OS sends that RST packet back to your client.


Common Causes and How to Fix Them

Here are the most frequent reasons you'll see this error, ordered from most common to least.

Cause 1: The Server Isn't Running (Most Common)

This is the #1 cause. You have a client script, but you haven't started the server script yet.

Example of the error:

python socket 10061-图3
(图片来源网络,侵删)
# Client script is running, but server script is not
$ python my_client.py
Traceback (most recent call last):
  File "my_client.py", line 10, in <module>
    s.connect(('127.0.0.1', 65432))
ConnectionRefusedError: [Errno 10061] No connection could be made because the target machine actively refused it

Fix: Start your server script first, in a separate terminal or using a process manager.

# Terminal 1: Start the server
$ python my_server.py
# Server is now waiting for a connection...
# Terminal 2: Run the client
$ python my_client.py
# Client connects successfully!

Cause 2: The Server is Listening on the Wrong Address or Port

Your server might be running, but it's not listening where the client is looking. This often happens with the IP address.

  • Using localhost vs. 0.0.1 vs. 0.0.0:

    • localhost and 0.0.1 refer to the local machine. They are equivalent.
    • 0.0.0 is a special address that means "listen on all available network interfaces" (i.e., 0.0.1 and the machine's local network IP).
    • If your server binds to 0.0.1, a client on the same machine can connect using 0.0.1 or localhost.
    • If your server binds to 0.0.1, a client on a different machine on the network cannot connect to it. It must use the server's actual LAN IP (e.g., 168.1.50).
    • If your server binds to 0.0.0, it accepts connections from both local and remote clients.
  • Port Mismatch: A simple typo in the port number is very easy to make.

Fix: Ensure your server binds to the correct address and port that your client is trying to connect to.

Server Code (Problematic): Listens only on localhost.

# server.py
import socket
HOST = '127.0.0.1'  # Or 'localhost'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print(f"Server listening on {HOST}:{PORT}")
    # ... accept connection ...

Client Code (Trying to connect from another computer):

# client.py (on another PC)
import socket
HOST = '192.168.1.50' # The server's LAN IP
PORT = 65432
# This will fail with 10061 because the server is not listening on its LAN IP

Server Code (Fixed): Listens on all interfaces.

# server.py (Fixed)
import socket
HOST = '0.0.0.0'  # Listen on all available network interfaces
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print(f"Server listening on all interfaces, port {PORT}")
    # ... accept connection ...

Cause 3: The Server is Crashed or Not Accepting Connections

Your server script might have started, but then it crashed due to an error before it could call s.listen() or s.accept(). The port is technically "in use" by the now-dead process, but it's not actually listening.

Fix:

  • Run your server from a terminal so you can see any error messages that cause it to crash.
  • If it crashes, fix the bug and restart it.
  • On Linux/macOS, you can check if a port is still being held by a crashed process with netstat -tuln | grep :PORT or lsof -i :PORT. If you see a process in a "TIME_WAIT" state or a zombie process, you may need to wait for it to release the port or kill it.

Cause 4: Firewall or Security Software

A firewall on the server machine is blocking the incoming connection on the specified port.

Fix:

  • Windows Defender Firewall: Go to "Allow an app through Windows Defender Firewall" and make sure your Python interpreter (e.g., python.exe) or your script is allowed for both Private and Public networks.
  • Third-party Antivirus/Firewall: Temporarily disable it to see if that's the cause. If it is, you'll need to add an exception for the port or the application.
  • Cloud Provider (AWS, Azure, GCP): If your server is on a cloud VM, you must configure the Security Group (AWS) or Network Security Group (Azure) to allow inbound traffic on the specific port.

A Complete, Working Example

To solidify your understanding, here is a simple echo server and client.

The Server (server.py)

This server listens on all interfaces (0.0.0) and echoes back any message it receives.

# server.py
import socket
HOST = '0.0.0.0'  # Symbolic name meaning all available interfaces
PORT = 65432        # Port to listen on
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print(f"Server listening on {HOST}:{PORT}")
    conn, addr = s.accept()
    with conn:
        print(f"Connected by {addr}")
        while True:
            data = conn.recv(1024)
            if not data:
                break
            print(f"Received from client: {data.decode('utf-8')}")
            conn.sendall(data) # Echo the data back
        print("Client disconnected.")

The Client (client.py)

This client connects to the server and sends a message.

# client.py
import socket
HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 65432        # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    message = b"Hello, world!"
    print(f"Sending: {message.decode('utf-8')}")
    s.sendall(message)
    data = s.recv(1024)
print(f"Received: {data.decode('utf-8')}")

How to Run:

  1. Save both files.
  2. Open Terminal 1 and run the server: python server.py
    • Output: Server listening on 0.0.0.0:65432
  3. Open Terminal 2 and run the client: python client.py
    • Output: Sending: Hello, world! followed by Received: Hello, world!
  4. Look back at Terminal 1. You'll see the server's log: Connected by ('127.0.0.1', 54321) and Received from client: Hello, world!.

If you try to run the client before the server, you will get the ConnectionRefusedError: [Errno 10061].

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