CodexBloom - Programming Q&A Platform

How to implement guide with handling concurrent tcp connections in python with socketserver

๐Ÿ‘€ Views: 59 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-07
python sockets socketserver Python

I've tried everything I can think of but I'm working on a TCP server using Python's `socketserver` module (version 3.9.7), and I'm running into issues with handling concurrent connections... My server seems to hang when multiple clients try to connect simultaneously. Hereโ€™s a simple version of what I have: ```python import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print(f"Received: {self.data}") self.request.sendall(self.data.upper()) if __name__ == '__main__': HOST, PORT = 'localhost', 9999 with socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) as server: print(f'Serving on {HOST}:{PORT}') server.serve_forever() ``` When I run this server and try to connect from multiple clients (using a simple script that sends messages in a loop), I notice that while the first client connects successfully, subsequent clients either hang or get a timeout behavior: ``` ConnectionRefusedError: [Errno 111] Connection refused ``` I've tried increasing the backlog in `ThreadingTCPServer` by modifying the constructor, but it didnโ€™t seem to help. My client script looks like this: ```python import socket HOST, PORT = 'localhost', 9999 for i in range(10): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.connect((HOST, PORT)) sock.sendall(b'Hello World') response = sock.recv(1024) print(f'Response: {response}') ``` Iโ€™ve also checked the system's maximum number of open files and adjusted it, but the scenario continues. Is there something I'm missing in the way Iโ€™m handling connections? Any advice on best practices for setting up a concurrent TCP server would be greatly appreciated! This is for a desktop app running on Ubuntu 22.04. Am I missing something obvious? I'd really appreciate any guidance on this.