1

Problem: packages are sent with the correct format, but received wrongly

I've been doing this assignment for a couple of hours from now and I'm struggling to understand why is this problem happening:

Basically, I need to do the following steps:

  1. Read 500 bytes from a file
  2. Pack the package number with the 500 bytes read
  3. Send the formatted bytes string to the socket address

So, my code looks like this:

sender.py:

def sending(host, port, path_to_file, package_size):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))
    fp = open(path_to_file, 'rb')
    start_time = time.time()
    package_number = 1
    while True:
        msg = fp.read(package_size)
        if len(msg) < package_size:
            sock.send(pack(f'I{len(msg)}s', package_number, msg))
            break
        final_result = pack(f'I{package_size}s', package_number, msg)
        sock.send(final_result)
        package_number += 1
    end_time = time.time()
    print(f"Time elapsed using {package_size} bytes: {end_time - start_time}")

receiver.py

def receive(host, port, extension, package_size):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, port))
    sock.listen(1)
    conn, addr = sock.accept()
    print("Connection accepted with " + str(addr))
    fp = open(f'received_file_{package_size}.{extension}', 'wb')
    start_time = time.time()
    while True:
        received_package = conn.recv(package_size)
        if len(received_package) < package_size:
            package_number, msg = unpack(f'I{len(received_package)-4}s', received_package)
            print(f"Package number {package_number} received with size {len(received_package)}")
            fp.write(msg)
            break
        package_number, msg = unpack(f'I{package_size-4}s', received_package)
        print(f"Package number {package_number} received with size {len(received_package)}")
        fp.write(msg)
        if not received_package:
            break
    fp.close()
    end_time = time.time()
    print(f"Time elapsed using {package_size} bytes: {end_time - start_time}")

But, the bytes I'm receiving from the sender looks like this:

Package number 1 received with size 500: (Correct package number one)
 b'\x01\x00\x00\x00\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x0f ...
Package number 2468486165 received with size 500: (Should be the second package)
 b'\x15\x1c"\x93\x02\x00\x00\x00\xd6\x05\x1ei\x1fv\xb1\xdf\xbb\x1a

Notice that the bytes representing the number are a little bit shifted to the right ("\x02\x00\x00\x00"), so the package number is also wrong (2468486165 instead of 2)

The file I'm trying to send is a 7MB png file. Also, I know that there is a FTP lib for this problem, but I need to do the same function without it.

What am I doing wrong?

Kresnik
  • 93
  • 1
  • 2
  • 9

0 Answers0