I have a python script where the server receives a large file. It works well but I have a problem to stop listening for more data. The socket is blocked because after the last transmission of data (e.g. 14 bytes), the socket tries in a loop to receive more data. This is the reason why it hangs at this position.
while True:
try:
(clientsocket, address) = serversocket.accept()
print('Got connection from', address)
data = clientsocket.recv(4096)
print("REVEIVING DATA")
print("data=%s",len(data))
if not data:
print("NEVER REACHED")
break
One workaround might be:
if len(data) < buffersize:
break
to get out of the loop. The problem is if the last package has the same size as buffersize. What is the best way to prevent clientsocket.recv blocking the script if there is no more data? Do I have to transmit the file size before?
Edit: I though about using a non-blocking socket. When I try this by using the command clientsocket.setblocking(0), the recv method is not blocked. But I get the problem that the data is read until there is not more data (e.g. 1024 in 1st iteration, 1024 bytes in 2nd iteration and the last 14 bytes in third iteration). Then it raises an exception which could be catched to close the written file. This works. But I have a problem if I start the server, connect a client and send data. If the server does not receive bytes during the first iteration, it raises an exception. So I cannot guarantee that there are data for the first call of recv. Furthermore the statement if not data is never called. Do you know how I could get it called?