简体   繁体   中英

Connection reset by peer when testing web server on different computers

I am testing a Python web server. 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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