Reputation: 331
I have a python server which receive image continuosly from a client. For each image, I need to save it to disk and create a csv with the image path and a integer value for each of them. My problem is that while the image is saving to disk, I reset the array of bytes..so only the top part of the image is visible, because I clear the array while the pc is still saving the image. how do i know when the file has been saved completely?
conn, addr = s.accept()
print('Connect with ' + addr[0] + ':' + str(addr[1]))
data = b''
while True:
buf = conn.recv(4096)
data = data + buf
if len(buf) < 4096:
date_string = str(datetime.datetime.now().timestamp()).replace('.', '')
with open('./images/' + date_string + '.jpg', 'ab') as f:
f.write(data)
data = b''
conn.send(str.encode("OK\n"))
UPDATE:
I try to explain better the situation:
From an android device (client) I capture continuos frame from the camera, that I need to post-process for machine learning. Each frame the device captures, will be send to the python server(code above). Before the client(the smartphone) sends the next frame, I have to make sure that the previous one was saved to the disk (the computer hdd). In fact, the line "conn.send(str.encode("OK\n")) need to say to the client "Ok, I saved the image, you can send me the next one". But before to clean the data variable, that contains the actual image, I have to make sure that f.write() has finished.
Upvotes: 1
Views: 401
Reputation: 770
After checking the documentation it seems like you should not check for the size of your data, instead you should just append until you are not receiving data anymore:
conn, addr = s.accept()
print('Connect with ' + addr[0] + ':' + str(addr[1]))
data = b''
while True:
buf = conn.recv(4096)
if buf:
data = data + buf
conn.send(str.encode("OK\n"))
else:
break
date_string = str(datetime.datetime.now().timestamp()).replace('.', '')
with open('./images/' + date_string + '.jpg', 'ab') as f:
f.write(data)
Maybe there is some packages inbetween that are not the same size but are not meant to be the last package. Also this has further advantages since you never need to reset your data variable.
Upvotes: 1