-2

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

Lucy Gu
  • 369
  • 1
  • 3
  • 10
  • 4
    How do you know that the `break` statement is executed? Have you tried adding more `print` statements to see what `sentence` is and to check when the `except` clause is entered? How do you know that the multiple lines of "inside" printed are not from different iterations of the *outer* loop? – kaya3 Feb 01 '21 at 00:16

2 Answers2

2

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).

Peter Gibson
  • 19,086
  • 7
  • 60
  • 64
0

I'm not sure why you're not breaking out of the loop, but—assuming the error actually fires—you can just jump out of it with your exception:

while True:
    print('here')
    connectionSocket, addr = serverSocket.accept()
    try:
        while True:
            print('inside')
            sentence = connectionSocket.recv(1024).decode()
    except EOFError:
        connectionSocket.close()
dpwr
  • 2,732
  • 1
  • 23
  • 38
Jordan Mann
  • 402
  • 6
  • 16