socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host (python2.7)

11,024

When a client does a graceful close of the socket such as client_socket.shutdown(socket.SHUT_WR) the server will receive all data and then its next recv call will get 0 bytes. You've coded for this case.

When the client exits without a graceful shutdown, the underlying socket implementation will do an ungraceful termination which includes sending a RESET to the server. In this case, the server gets the exception you've seen. It means that at the socket level there is no guarantee that the server received all of its data.

You should update your client to be graceful about closing and also decide what your policy should be on ungraceful exit.

Share:
11,024
Daniel david
Author by

Daniel david

Updated on June 07, 2022

Comments

  • Daniel david
    Daniel david almost 2 years

    I have a problem with my socket , it is well functioning but when i close the client / close the client window the server lost the connection ( the server needs to stay open and wait for other connection)

    while True:
        rlist, wlist, xlist = select.select([server_socket]+open_client_sockets, open_client_sockets, [])
        for current_socket in rlist:
            if current_socket is server_socket:
                (new_socket, address) = server_socket.accept()
                open_client_sockets.append(new_socket)
                print 'new member : ' + str(address)
            else:
                data = current_socket.recv(1024)
                print data
                if data == "":
                    open_client_sockets.remove(current_socket)
                    print 'Connection with client closed.'
    
                else:
                    send_messages(data)
    

    The problem is in this part -

    if data == "":
                    open_client_sockets.remove(current_socket)
                    print 'Connection with client closed.
    

    This is the error -

    data = current_socket.recv(1024)
    error: [Errno 10054] An existing connection was forcibly closed by the remote host
    

    I didn't get this error in my previous socket

  • Daniel david
    Daniel david about 8 years
    How do I know that the server gets an ungraceful termination ? @tdelaney
  • tdelaney
    tdelaney about 8 years
    You get the exception. It should be sufficient to wrap sends and recvs in try/except blocks that catch socket.error. The actual error differs between linux and windows (10054 suggests you are on windows) but checking for 10054 and 54 and re-raising others should do it.