如何实现Python持续稳定的Server-Client连接?解决ConnectionResetError问题
Hey there! Let's work through how to build a persistent Server-Client connection and fix that annoying ConnectionResetError you're seeing.
实现持久化Server-Client长连接 & 解决ConnectionResetError
Why You're Getting That Error
That ConnectionResetError: [WinError 10054] pops up for a few key reasons with your current code:
- You aren't handling unexpected connection drops (e.g., if the client crashes, the server still tries to send data to a dead connection)
- There's no check for empty data from
recv()—when a connection closes properly,recv()returns an empty byte string, and your code doesn't handle this edge case - Sending/receiving nonstop without any delay can overload network buffers, forcing the system to terminate the connection
Fixed Code Implementation
Server Side (Supports Persistent Single-Client Connection with Reconnect Logic)
import socket import time host = '0.0.0.0' # Listen on all available network interfaces port = 12345 # Use an unused port of your choice def run_server(): while True: try: # Initialize socket and enable port reuse (avoids "address in use" errors on restart) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(1) print(f"Server started, waiting for client connection at {host}:{port}...") conn, addr = s.accept() print(f"Client {addr} connected successfully") # Persistent connection loop while True: # Send message to client send_msg = "Test message from server" conn.send(send_msg.encode('utf-8')) print(f"Sent: {send_msg}") # Receive client message with timeout to avoid infinite blocking conn.settimeout(30) # Adjust timeout duration as needed try: recv_data = conn.recv(1024) if not recv_data: # Empty response means client disconnected print("Client disconnected") break print(f"Received from client: {recv_data.decode('utf-8')}") except socket.timeout: print("Receive timeout, keeping connection alive") time.sleep(1) # Add delay to prevent overwhelming network buffers # Clean up connection on exit conn.close() s.close() except Exception as error: print(f"Error occurred: {str(error)}") time.sleep(2) # Wait before restarting to avoid rapid loops if __name__ == "__main__": run_server()
Client Side (Persistent Connection with Auto-Reconnect)
import socket import time server_host = '127.0.0.1' # Replace with your server's actual IP port = 12345 # Must match the server's port def run_client(): while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((server_host, port)) print(f"Connected to server at {server_host}:{port}") # Persistent connection loop while True: # Receive server message with timeout s.settimeout(30) try: recv_data = s.recv(1024) if not recv_data: # Empty response means server disconnected print("Server disconnected") break print(f"Received from server: {recv_data.decode('utf-8')}") except socket.timeout: print("Receive timeout, keeping connection alive") # Send message to server send_msg = "Test message from client" s.send(send_msg.encode('utf-8')) print(f"Sent: {send_msg}") time.sleep(1) # Add delay to prevent buffer overload # Clean up connection on exit s.close() except Exception as error: print(f"Error occurred: {str(error)}") print("Attempting to reconnect...") time.sleep(2) # Wait before retrying connection if __name__ == "__main__": run_client()
Key Improvements Made
- Port Reuse: Server uses
SO_REUSEADDRto avoid "address already in use" errors when restarting - Timeout Handling: Prevents the program from getting stuck indefinitely waiting for a response
- Connection State Checks: Detects when the other end disconnects by checking for empty
recv()responses - Auto-Reconnect Logic: Both server and client will automatically try to re-establish connections if they drop
- Throttling:
time.sleep()adds a small delay to avoid overwhelming network buffers
Extra Tips for Production Use
- Stick to a consistent encoding (we used
utf-8here) to avoid data corruption - For multi-client support, use multithreading/multiprocessing or async IO (like
asyncio) on the server - Add a heartbeat mechanism (small, regular "ping" messages) to detect silent connection drops
内容的提问来源于stack exchange,提问作者Mr.clock
相关产品推荐
相关产品推荐

