Search code examples
pythonmultithreadingclient-side-validation

Multithreading in such a way that I am able to accept multiple clients in Python


I am expected to write a server that can handle multiple clients in Python, and so far I am able to deal with one connection(from a client)but I really don't know how to extend my program to handle multiple clients. I tried looking at Twisted, but couldn't really grasp it.

Any recommendations, or sample code that can help me understand how to handle multiple clients? Ideally, I should be able to have multiple clients connected to the server, and based on the input they pass once they are connected, I should be able to do all sort of fascinating things by parsing their input, etc.

I really look forward to your responses, and thank you in advance for your time. I'm a long time lurker.

P.S I already looked at most other multithreading examples of Python, they didn't quite honestly help.

Thanks.


Solution

  • Use SocketServer with the ThreadingMixIn so each client connection is handled on a separate thread.

    Here's a starting point for you.

    import SocketServer
    
    PORT = 5000
    
    class Server(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
        daemon_threads = True
    
    class Handler(SocketServer.BaseRequestHandler):
        def handle(self):
            # TODO: handle this client
            # this sample acts as an echo server
            while True:
                data = self.request.recv(1024)
                if not data:
                    break
                self.request.sendall(data)
    
    if __name__ == '__main__':
        server = Server(('', PORT), Handler)
        server.serve_forever()