I'm trying to send files from server to client with the code here and doesn't succeed, the client gets stuck on the last recv. Server is done sending all the times. I've tried many things to try to solve:
sending 'STOP' when server is done sending -> client somehow receives the last bytes with 'STOP' and writes it to the file(even though they were different client.send() the client mixed it)
Sending how many bytes am I going to receive and then sending the bytes
Sending a pickle of [bytes, 'OK'/'STOP']
Server.py
host = '0.0.0.0'
port = 9898
s = socket.socket()
s.bind((host, port))
s.listen(1)
client, addr = s.accept()
def download_file(self, file_name, client):
with open(file_name, 'rb') as f:
file_name_without_path = file_name.split('\\')
file_name_without_path = file_name_without_path[len(file_name_without_path) - 1]
filesize = os.path.getsize(file_name)
client.send(pickle.dumps([file_name_without_path, filesize])) # send name and size of file
bytesToSend = f.read(1024)
client.send(bytesToSend)
print(bytesToSend)
bytes_sent = 0
while len(bytesToSend) != 0:
bytesToSend = f.read(1024)
bytes_sent += len(bytesToSend)
client.send(bytesToSend)
print(bytesToSend)
print('done')
Client.py
s = socket()
PORT = 9898
s.connect(('127.0.0.1', PORT))
def download(self, path):
filename, filesize = pickle.loads(s.recv(1024))
new_file_path = path + '\\' + filename
f = open(new_file_path, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while data != ''.encode():
print('before')
data = s.recv(1024)
print(data)
print('after')
totalRecv += len(data)
percetage = (totalRecv / filesize) * 100
print(str((totalRecv / filesize) * 100) + "%")
f.write(data)
if percetage >= 100:
break
f.close()
print('done')