2

i am currently trying to go through a basic tutorial on networking and i noticed that a rudimentary client/server program would freeze upon the server trying to read more data from the client when all the data is received . Basically the code looks like this :

def recv_all(sock,length):
    data=''
    while len(data)<length:
        more=sock.recv(length-len(data))
        if not more :
            raise EOFError('socket inchis %d octeti intr-un mesaj de %d octeti'%(len(data),length))
        data+=more
    return data

This function is called from both client and server but the server will use it first to process the client request. All goes fine until the second call to sock.recv , when the request message has been received.

Instead of jumping to the next line (with more being 0) the debugger just freezes there and i have no idea what the reason for that might be.

My OS is Windows XP if this is relevant in any way. Any help would be appreciated, Thanks

4
  • 1
    Are the sockets non-blocking? Commented Mar 19, 2012 at 12:55
  • 2
    That's just how sockets work, they block by default. You can use select to check if there's data to read in the socket, or use non-blocking IO. Commented Mar 19, 2012 at 13:02
  • 1
    so what actually happens when i call recv(1024) and there are exactly 1024 bytes to be read? is there no way to know if there is any more data? Commented Mar 19, 2012 at 13:38
  • that is correct. That's why protocols exist: to provide a structured way to interconnect two systems based on very simple (and sometimes annoying) primitives Commented May 18, 2012 at 22:45

1 Answer 1

4

As others have pointed out, the cause is the fact that sockets are blocking by default. It means that the recv function will block the execution of the program until some data arrive. Unless things are changed, the program will wait forever, or until the server breaks the connection.

One solution is to switch to non-blocking sockets, using the settimeout function, like this sock.settimeout(2). This means that if nothing is received within 2 seconds, an exception will be thrown. You can catch that exception and handle it accordingly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.