0

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:

  1. 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)

  2. Sending how many bytes am I going to receive and then sending the bytes

  3. Sending a pickle of [bytes, 'OK'/'STOP']

That's what happens when running the code

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')
  • TCP does not preserve message boundaries (or at least there is no guarantee -- sometimes it works out due to fortuitous timing). You will need to "frame" the file data appropriately. Check out this answer for an explanation and then rework your question above if necessary. https://stackoverflow.com/questions/9563563/what-is-a-message-boundary – Gil Hamilton May 13 '20 at 19:44
  • Thank you! Solved. – Ron Rozenblum May 13 '20 at 20:33

0 Answers0