You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中出现"Connection refused"错误怎么办?现有方案无法解决

Hey there, let's break down why you're hitting that "Connection refused" error with your SSL client code, and how to fix it:

First, the root cause of "Connection refused"

This error almost always means your client can't establish a basic TCP connection to the target address/port—there's no server listening on 127.0.0.1:3001 when your client tries to connect. The SSL handshake hasn't even started yet; this is a lower-level network issue.

Step-by-step fixes & checks

1. Make sure you have a running SSL server on port 3001

You only shared the client code, but without a server listening on that port, the client has nothing to connect to. Here's a minimal working SSL server that pairs with your client (it handles the addition logic too):

import ssl
import socket

def process_client(ssl_conn):
    # Receive input from client
    input_data = ssl_conn.recv(1024).decode().strip()
    try:
        # Split input into two numbers
        num1, num2 = map(int, input_data.split())
        result = str(num1 + num2).encode()
        ssl_conn.send(result)
    except ValueError:
        ssl_conn.send(b"Error: Please enter two valid numbers separated by space")
    ssl_conn.close()

# Configure SSL context for server
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
# Load server's certificate and private key (you'll need these files)
context.load_cert_chain(certfile="server_cert.pem", keyfile="server_key.pem")
# Load the same CA cert your client uses (scert.pem) to verify clients
context.load_verify_locations("scert.pem")

# Start listening for connections
port = 3001
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind(('127.0.0.1', port))
    sock.listen(5)
    print(f"SSL Server running on 127.0.0.1:{port}")
    while True:
        client_sock, client_addr = sock.accept()
        # Wrap the incoming connection with SSL
        ssl_connection = context.wrap_socket(client_sock, server_side=True)
        process_client(ssl_connection)
  • Note: You'll need valid SSL files (server_cert.pem, server_key.pem, and scert.pem). If you're testing locally, you can generate self-signed certificates using OpenSSL.

2. Verify the port is actually being listened on

Before running your client, check if any process is using port 3001:

  • On Linux/macOS: Run netstat -an | grep 3001 or lsof -i :3001
  • On Windows: Run netstat -ano | findstr :3001
    If no results show up, your server isn't running correctly.

3. Check firewall settings

Local firewalls (like Windows Firewall or ufw on Linux) might block connections to port 3001. Temporarily disable the firewall for testing, or add an inbound rule to allow traffic on port 3001.

4. Tweak your client code for better error handling

Add exception catching to make debugging easier, so you don't get a messy traceback every time:

import ssl
import socket

port = 3001
while True:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ssl_socket = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED, ca_certs='scert.pem')
        ssl_socket.connect(('127.0.0.1', port))
        
        user_input = input("Enter two numbers to add: ")
        ssl_socket.write(user_input.encode())
        
        response = ssl_socket.recv(1024)
        print(response.decode())
        
        ssl_socket.close()
    except ConnectionRefusedError:
        print("Oops! Connection refused. Double-check that your server is running on 127.0.0.1:3001")
        break  # Or add time.sleep(1) to retry automatically
    except Exception as e:
        print(f"Unexpected error: {str(e)}")
        if 'ssl_socket' in locals():
            ssl_socket.close()

Final notes

Once your server is up and running, and the port is accessible, the "Connection refused" error should go away. If you hit SSL-related errors after that, we can dig into certificate issues—but let's get the basic connection working first!

内容的提问来源于stack exchange,提问作者Pratyush Ranjan Tiwari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:13:53