Search code examples
pythonsocketssocketserver

stop recv from socket if no data is available


I am trying to stop recv from waiting endlessly for input.

First I tried:

recv = bytes('','UTF-8')

while True:
    data_recv = self.socketclient.recv(1024*768)
    if not data_recv:
        break

    else:
        recv += data_recv

return recv

On Serverside I send a picture and then the server just waits after host.sendall(string). So I thought after a couple of receives (since the picture is bigger the client has to receive more often) it will detect data_recv == false and stops but it doesn't happen.

My second try was with select()

do_read = False
recv = bytes('','UTF-8')

while True:
    read_sockets,write_sockets,error_sockets = select.select([self.socketclient],[],[])
    do_read = bool(read_sockets)
    print (do_read)
    if do_read:
        print ("read")
        data_recv = self.socketclient.recv(640*480)
        recv += data_recv
    else:
        break

return recv

With this he only reads True from print(do_read) and then also just stops and waits endlessly. Here too I had expected to read False at some point.

So my question is how do I manage it, that my client reads the entire string from the socket and if nothing is send anymore it stops?

I had some success with self.socketclient.settimeout() but I rather would not use it since it will always waste time in the programm and it is more like a workaround.


Solution

  • You have to stop your while loop when all data is received. So after each recv you have to check if received data length is the length of file you requested. If it is, then you break the loop and do something with that data.

    recv has no knowledge if sending of data is done, because it doesn't know how long data is. It is just listening forever until you or other endpoint close connection.

    You can also use non-blocking socket (which is better by the way).