简体   繁体   English

在其他计算机上测试Web服务器时,对等方重置连接

[英]Connection reset by peer when testing web server on different computers

I am testing a Python web server. 我正在测试Python Web服务器。 It works as expected using localhost as the server and client, but when I test on different computers, I am getting 使用本地主机作为服务器和客户端,它可以按预期工作,但是当我在其他计算机上进行测试时,

[Errno 54] Connection reset by peer about 20% - 80% of the time, depending on how many client threads I spawn at once. [Errno 54]对等方大约20%-80%的时间重置连接 ,具体取决于我一次生成的客户端线程数。 Why? 为什么?

Code Snippets 代码段
Server listens: 服务器监听:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((self.interface, self.port))
sock.listen(5)

Server loops forever, accepts client connection, spawns new thread: 服务器永远循环,接受客户端连接,产生新线程:

while True:
    (clientsock, (ip, port)) = self.sock.accept()
    newthread = ClientThread(ip, port, clientsock)              
    newthread.start()

Spawn a bunch of client threads which connect with server, send message which requests a file, and then closes connection 产生一堆与服务器连接的客户端线程,发送请求文件的消息,然后关闭连接

Server sends message to client when ready 服务器准备就绪后会向客户端发送消息

self.socket.sendall(message.encode())

After message is sent, close the write end of connection: 发送消息后,关闭连接的写入端:

self.socket.shutdown(socket.SHUT_WR)

Client receives message (error occurs here) 客户端收到消息(此处发生错误)

def receive(self):
    data_string = ''
    bytes = self.sock.recv(self.bufsize)
    while len(bytes) > 0:
        bytes_str = bytes.decode('UTF-8')
        data_string += bytes_str
        bytes = self.sock.recv(self.bufsize)
    return data_string

After client thread has received message, close the connection: 客户端线程收到消息后,关闭连接:

self.socket.close()

Receive function had errors. 接收功能有错误。 Changed to this: 改为:

def receive(self):
    data_string = ''
    while True:
        bytes = self.sock.recv(self.bufsize)
        bytes_str = bytes.decode('UTF-8')
        data_string += bytes_str
        if not bytes:                   
            break
    return data_string

Old receive function would try to call recv a second time when server had already closed socket. 服务器已关闭套接字时,旧的接收函数将尝试第二次调用recv New one only calls once. 新的仅呼叫一次。

Also did not know you could increase listening socket backlog > 5 since Python docs say generally 5 is max, when on OS X it is 128. Increasing backlog to 128 helped. 还不知道您可以将侦听套接字积压增加到5以上,因为Python文档通常说最大5是最大值,而在OS X上是5。将积压增加到128有帮助。

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

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