Python sock.listen(…)

2024-05-15 03:53:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python文档中看到的所有关于sock.listen(5)的例子都表明,我应该将最大backlog数设置为5。这给我的应用程序带来了问题,因为我期望一些非常高的容量(许多并发连接)。我将它设置为200,并且在我的系统上没有看到任何问题,但是我想知道在它引起问题之前我可以设置多高。。

有人知道吗?

编辑:这是我的accept()循环。

while True:    
    try:
        self.q.put(sock.accept())
    except keyboardInterrupt:
        break
    except Exception, e:
        self.log("ERR %s" % e)

Tags: 文档selftrue应用程序编辑系统listen例子
2条回答

医生这么说

socket.listen(backlog) Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).

显然,系统值在您的系统上大于5。我不明白为什么设置一个更大的数字会是一个问题。可能为每个排队的连接保留了一些内存。

我的linux手册页上有这样的内容

If the backlog argument is greater than the value in /proc/sys/net/core/somaxconn, then it is silently truncated to that value; the default value in this file is 128. In kernels before 2.4.25, this limit was a hard coded value, SOMAXCONN, with the value 128.

您不需要将参数listen()调整为大于5的数字。

参数控制允许有多少未完成的非accept()ed连接。参数listen()与并发连接的套接字的数量无关,只与进程尚未accept()创建的并发连接的数量有关。

如果将参数调整为listen()会对代码产生影响,则表明每次调用accept()之间都会发生太多延迟。然后,您需要更改您的accept()循环,使其具有更少的开销。

在您的例子中,我猜self.q是一个python queue,在这种情况下,您可能需要调用self.q.put_nowait(),以避免在这个调用中阻塞accept()循环的任何可能性。

相关问题 更多 >

    热门问题