简体   繁体   English

如何在SocketServer中设置最大连接数

[英]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 . 我试图找到一种方法如何设置限制 - 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. 例如最多3个客户。

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. 缩小尺寸是接受新TCP连接然后关闭。 Hope that's OK. 希望没关系。

The code I'm using in a server NOT based on a SocketServer looks basically like this: 我在不基于SocketServer的服务器中使用的代码看起来基本上是这样的:

A variable is needed: 需要一个变量:

accepted_sockets = weakref.WeakSet()

The WeakSet has the advantage that no longer used elements get deleted automatically. WeakSet的优点是不再使用不再使用的元素。

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. 您必须调整它以便与SocketServer一起使用(例如,TCP套接字在那里被称为request ,可能是服务器处理socket.close等),但希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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