简体   繁体   中英

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.

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(self):
     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 (eg the TCP socket is called request there, probably the server handles the socket.close, etc.), but hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM