简体   繁体   English

当套接字侦听积压较小时,Python 中的对等方重置连接

[英]Connection reset by peer in Python when socket listen backlog is small

I have the following code, run with Python 2.7 (on Mac OS) (needed because it's going into a legacy application).我有以下代码,使用 Python 2.7(在 Mac OS 上)运行(需要,因为它将进入遗留应用程序)。 If LISTEN_BACKLOG is less than the number of clients, then after a few iterations I will get a "Connection reset by peer" on one of the clients during the recv() call, and sometimes during the connect().如果 LISTEN_BACKLOG 小于客户端数量,那么经过几次迭代后,在 recv() 调用期间,有时在 connect() 期间,我将在其中一个客户端上获得“对等连接重置”。

For example, if you run 1 instance of the server and 2 instances of the client, with LISTEN_BACKLOG = 1, then you will get the issue very quickly.例如,如果您运行 1 个服务器实例和 2 个客户端实例,并且 LISTEN_BACKLOG = 1,那么您将很快发现问题。

server.py服务器.py

import socket

LISTEN_BACKLOG = 1

exit_condition = False
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(('127.0.0.1', 12345))
listener.settimeout(0.2)
listener.listen(LISTEN_BACKLOG)

while not exit_condition:
    try:
        server = listener.accept()[0]
        server.send(' ')
        server.close()
    except socket.timeout:
        # Timed-out connection so go around and wait again
        pass

client.py客户端.py

while True:
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(('127.0.0.1', 12345))
    print "Connected"
    data = client.recv(1) # <-- Get "Connection reset by peer" here sometimes
    if data == ' ':
        print "Got Data"
    else:
        print "ERROR: Received data is wrong: ", data, "\n"
        break

    client.close()
    print "Closed"

I am using a small socket timeout for the socket accept on the server, because I need to periodically check an exit condition for the while loop in the larger application.我正在为服务器上的套接字接受使用一个小的套接字超时,因为我需要定期检查较大应用程序中 while 循环的退出条件。 I know this is not ideal, but regardless I would expect it to work.我知道这并不理想,但无论如何我都希望它起作用。

Can you please help me understand why the "Connection reset by peer" occurs?你能帮我理解为什么会发生“对等连接重置”吗?

EDIT: I have also tried an updated version of my code with Python3 and the behaviour is the same: "Connection reset by peer" at the recv() line.编辑:我还尝试使用 Python3 更新我的代码版本,行为是相同的:recv() 行中的“对等连接重置”。

If anyone else is coming across the same issue, I believe it is only a problem on MacOS.如果其他人遇到同样的问题,我相信这只是 MacOS 上的问题。 Perhaps the python socket implementation has a bug in MacOS.也许python套接字实现在MacOS中存在错误。 I've tried on Linux and I cannot reproduce the issue there.我已经在 Linux 上尝试过,但无法在那里重现该问题。

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

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