Reputation: 23
This code downloads most of the file but not all of the file (inside a while loop) any idea what I'm doing wrong?
data = csocket.recv(1024)
with open(filename, 'wb') as file_to_save:
while data:
file_to_save.write(data)
time.sleep(.008)
data = csocket.recv(1024)
if len(data) < 1024:
break
This code downloads roughly 600 bytes short when downloading 38,616 bytes size file.
Upvotes: 1
Views: 2342
Reputation: 905
Normally the recv() function does not guarantee to return the total amount of bytes you "request". The argument is just a maximum amount of bytes that you expect to receive, but the function can return less bytes than this if they are available in the buffer. Here it is an implementation from https://docs.python.org/3/howto/sockets.html
def myreceive(self):
chunks = []
bytes_recd = 0
while bytes_recd < MSGLEN:
chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
if chunk == b'':
raise RuntimeError("socket connection broken")
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
return b''.join(chunks)
As you can see the function repeats the recv() until the expected amount of bytes arrives. After each chunk arrives, the new recv() quests as maximum amount of bytes MSGLEN – bytes_recd
. The min() is used to limit the amount for received bytes for each block to 2048. When the recv() function returns 0 bytes (chunk == b''), it means that the other side closed the connection.
For your case the len(data)
can a will return sometimes return less than 1024. your break condition should be if len(data) < 1:
Upvotes: 3