pythonbreakexcepteoferror

Why break wouldn't break out of whileloop in except clause


So I am writing code for a simple socket

    while True:
        print('here')
        connectionSocket, addr = serverSocket.accept()
        while True:
            print('inside')
            try:
                sentence = connectionSocket.recv(1024).decode()
            except EOFError:
                connectionSocket.close()
                break

The idea is that once the client sends EOF, connection socket is closed and we break out of the while loop and wait for next client to connect. What I don't get is that, when I try running this and sending an EOF to the server, the server side start looping forever and printing "inside". No "here" was printed so I'm sure I never broke out of the inner for loop. Why is that? Ignoring everything else that I might have done wrong why is "break" not breaking out of the while loop?? Thanks


Solution

  • Take a read of this page on using sockets in Python https://docs.python.org/3/howto/sockets.html#using-a-socket

    The API for socket.recv doesn't raise an EOFError. Instead you should check for an empty response.

    sentence = connectionSocket.recv(1024).decode()
    if sentence == '':
        break
    

    Note that recv is also not guaranteed to receive your data all at once, so you typically want to loop and buffer the incoming data. It will only return an empty string once the other end has closed the connection (or the connection is lost), so make sure the sender is closing the socket (or otherwise marking the end of data somehow).