pythonpython-2.7socketssocketserver

How to set max number of connections in SocketServer


I'm trying to find a way how to set a limit - maximum number of connections in SocketServer.

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    daemon_threads = True


class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        some code 

Is there some way how to do that? For example maximum 3 clients.


Solution

  • The simplest solution is to count active connections and simply stop serving new connections when the limit is reached. The downsize is that the new TCP connections are accepted and then closed. Hope that's OK.

    The code I'm using in a server NOT based on a SocketServer looks basically like this:

    A variable is needed:

    accepted_sockets = weakref.WeakSet()
    

    The WeakSet has the advantage that no longer used elements get deleted automatically.

    A trivial helper function:

    def count_connections():
         return sum(1 for sock in accepted_sockets if sock.fileno() >= 0)
    

    And the usage in the request handling code is straightforward:

       if count_connections() >= MAX_CONN:
            _logger.warning("Too many simultaneous connections")
            sock.close()
            return
        accepted_sockets.add(sock)
        # handle the request
    

    You have to adapt it for use with SocketServer (e.g. the TCP socket is called request there, probably the server handles the socket.close, etc.), but hope it helps.