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

Mac平台Python运行服务器遇Connection refused错误及功能实现咨询

Hey there! Let's tackle your two issues one by one: fixing that annoying "Connection Refused" error first, then building the login system that saves passwords to a text file.

1. Fixing the "Connection Refused" Error on Mac

First up, let's troubleshoot why your client can't connect to the server. Here are the most common fixes and checks:

  • Start the server before the client: It sounds obvious, but this is the #1 cause of this error. Double-check that you run your server script first—if the client tries to connect before the server is listening, it'll get rejected.
  • Match host and port on both sides: If your server binds to localhost (127.0.0.1), the client must connect to the exact same host. If you're using your Mac's local network IP (like 192.168.x.x), ensure both client and server use that. Also, make sure the port number is identical (avoid reserved ports below 1024 unless you run the server with sudo).
  • Check Mac's firewall: The built-in firewall might be blocking the connection. Head to System Preferences > Security & Privacy > Firewall, then either disable it temporarily to test, or add your Python interpreter to the allowed apps list.
  • Listen on the right network interface: If you want the server to accept connections from other devices (not just your Mac), use socket.bind(('0.0.0.0', port)) instead of localhost—this makes the server listen on all available network interfaces.

Here's a minimal working server skeleton to test connectivity:

import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))  # Use same host/port in client
server_socket.listen(5)

print("Server listening on localhost:12345")
client_socket, addr = server_socket.accept()
print(f"Connected from {addr}")

And the matching client to pair with it:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect(('localhost', 12345))  # Must match server's bind params
    print("Connected to server successfully!")
except ConnectionRefusedError:
    print("Error: Couldn't connect—make sure the server is running first!")
2. Building the Login System with Password Saving

Now let's implement the login flow: the client sends a username and password, the server stores them in a .txt file, and sends a confirmation back.

Server Side Code

This server will accept credentials from the client, append them to logins.txt, and send a success message:

import socket

def save_credentials(username, password):
    # Append to text file (creates the file if it doesn't exist)
    with open('logins.txt', 'a') as file:
        file.write(f"Username: {username}, Password: {password}\n")

def main():
    host = 'localhost'
    port = 12345

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(1)

    print(f"Login server running on {host}:{port}")
    client_socket, addr = server_socket.accept()
    print(f"Connected to client at {addr}")

    # Receive username and password from client
    username = client_socket.recv(1024).decode('utf-8').strip()
    password = client_socket.recv(1024).decode('utf-8').strip()

    # Save credentials to file
    save_credentials(username, password)
    print(f"Saved credentials for user: {username}")

    # Send confirmation to client
    client_socket.send(b"Login successful! Your credentials have been saved.")

    # Clean up connections
    client_socket.close()
    server_socket.close()

if __name__ == "__main__":
    main()

Client Side Code

This client prompts the user for their login details, sends them to the server, and displays the server's response:

import socket

def main():
    host = 'localhost'
    port = 12345

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((host, port))
    except ConnectionRefusedError:
        print("Error: Server not reachable—make sure it's running!")
        return

    # Get user input
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    # Send credentials to server
    s.send(username.encode('utf-8'))
    s.send(password.encode('utf-8'))

    # Receive and print server response
    response = s.recv(1024).decode('utf-8')
    print(response)

    s.close()

if __name__ == "__main__":
    main()

Critical Notes for Production Use

  • Never store plain-text passwords: The example above saves passwords as plain text, which is extremely insecure for any real-world application. For a safe system, use a password-hashing library like bcrypt to hash passwords before storing them. Here's a quick snippet of how to do that:
    import bcrypt
    
    def hash_password(password):
        salt = bcrypt.gensalt()
        return bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8')
    
    # Use this in save_credentials instead of plain password
    save_credentials(username, hash_password(password))
    
  • Add error handling: The code has basic error handling, but you'll want to expand it (e.g., handle broken connections, invalid input, or duplicate usernames) for robustness.
  • Check file permissions: On Mac, ensure your Python script has write access to the directory where logins.txt will be created.

内容的提问来源于stack exchange,提问作者Joseph

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:47:37