Reputation: 11
I am trying to send files from flutter app to a python server. But for some reason i cant able to do it. At 98.67% its getting stopped. If anyone can able help me with this then it would be great.
filename = sock.recv(1024)
if filename != "":
filesize = sock.recv(1024)
print(filesize)
f = open("client.jpg",'wb')
data = sock.recv(1024)gedit server.py
totalRecv = len(data)
f.write(data)
while data != '':
data = sock.recv(1024);
totalRecv += len(data)
f.write(data)
print("{0:.2f}".format((totalRecv/float(filesize))*100)+"% done")
print("download complete")
f.close()
sock.close()
above is my server code.
File file = await FilePicker.getFile();
socket.add(utf8.encode("RECV"));
//socket.add(utf8.encode(file.path));
print(file.path);
//print(file.lengthSync());
//socket.add(utf8.encode(file.lengthSync().toString()));
var bytes = file.readAsBytesSync();
socket.add(bytes);
socket.add(utf8.encode(""));
this is from my flutter project. please help. this is how its happening at the server
Upvotes: 1
Views: 511
Reputation: 5630
I don't know flutter, but if you can I would add an explicit close
command for the socket. It might be that the last bytes are just not flushed out.
If not working, then change your code for debugging.
# you receive bytes.
# but you want a string, so you have to decode
filename_bytes = sock.recv(1024)
filename = filename_bytes.decode("utf-8")
print("I received %d bytes and my filename is %r"
% (len(filename_bytes), filename))
if filename != "":
filesize = sock.recv(1024)
print("I got %d bytes and file size is %r"
% len(filesize), totalRecv)
filesize = int(filesize)
f = open("client.jpg",'wb')
data = sock.recv(1024)
totalRecv = len(data)
f.write(data)
while data != '':
data = sock.recv(1024)
totalRecv += len(data)
f.write(data)
print("{0:.2f}% done {1} bytes".format(
(totalRecv/filesize)*100, filesize))
print("download complete")
f.close()
sock.close()
So let's first look at your problem at hand, but as soon as it is solved you might read the rest of my answer.
By the way your protocol is kind of dangerous.
As far as I know you do not have any guarantee, that bytes arrive in the same chunk sizes in which they are sent. So network protocols should be written such, that even if you received the data byte per byte you would know where the filename ends and where the file size ends.
This is not the case.
Imagine the file name "test1", the file size "4", and the file contents "5ABC" This results in "test145ABC" Is the file name "test" and the file size "145" or is the filename "test14" and the file size "5". Impossible to know.
One option would be to send the filename, a termination character, the file size, a termination character and then the file contents or you use a binary protocol, whre you first send two bytes indicating the length of the file name, then the file name, then 4 bytes indicating the file size and then the file contents.
Upvotes: 2