i'm trying find way how set limit - maximum number of connections in socketserver
.
class threadedtcpserver(socketserver.threadingmixin, socketserver.tcpserver): daemon_threads = true class threadedtcprequesthandler(socketserver.baserequesthandler): def handle(self): code
is there way how that? example maximum 3 clients.
the simplest solution count active connections , stop serving new connections when limit reached. downsize new tcp connections accepted , closed. hope that's ok.
the code i'm using in server not based on socketserver
looks this:
a variable needed:
accepted_sockets = weakref.weakset()
the weakset has advantage no longer used elements deleted automatically.
a trivial helper function:
def count_connections(self): return sum(1 sock in accepted_sockets if sock.fileno() >= 0)
and usage in request handling code straightforward:
if count_connections() >= max_conn: _logger.warning("too many simultaneous connections") sock.close() return accepted_sockets.add(sock) # handle request
you have adapt use socketserver
(e.g. tcp socket called request
there, server handles socket.close, etc.), hope helps.
Comments
Post a Comment