Skip to content Skip to sidebar Skip to footer

Sending File Over UDP Divided Into Fragments

I have been dealing with sending file which is divided into fragments set by user on input. Problem is, I am getting error: rec_list[fragIndex - 1] = data IndexError: list assignm

Solution 1:

You tried to compare apples to oranges. Well, bytes to str but wikipedia doesn't say anything about that.

while contents!='':
    ...

contents is a bytes object and '' is a str object. In python 3, those two things can never be equal. Firing up the shell we see that

>>> b''==''
False
>>> 
>>> contents = b"I am the very model"
>>> while contents != '':
...     if not contents:
...         print("The while didn't catch it!")
...         break
...     contents = contents[3:]
... 
The while didn't catch it!

Since all objects have a truthiness (that is, bool(some_object) is meaningful) and bytes objects turn False when they are empty, you can just do

while contents:
    ....

UPDATE

Not part of the original answer but a question was raised about sending retries back to the client. The server side is sketched in here

while True:
            received_chunks = 0
            fragCount = -1
            rec_list = []
            while True:
                # wait forever for next conversation
                if fragCount == -1:
                    sock.settimeout(None)
                try:
                    data, addr = sock.recvfrom(65535)
                except socket.timeout:
                    # scan for blank slots in rec_list
                    retries = [i for i, data in rec_list if not data]
                    # packet is mType, numFrags, FragList
                    # TODO: I just invented 13 for retry mtype
                    sock.sendto(struct.pack("!{}h".format(len(retries+2)), 13,
                        len(retries), *retries)
                    continue
                # our first packet, set timeout for retries
                if fragCount == -1:
                    sock.settimeout(2)
                header = data[:18]
                data = data[18:]
                (mType, fragSize, fragIndex, fragCount, crc) = struct.unpack('!hIIII', header)

                print(
                '\nTyp: ' + str(mType) +
                '\nFragSize: ' + str(fragSize) +
                '\nFragIndex: ' + str(fragIndex) +
                '\nFragCount: ' + str(fragCount) +
                '\nCRC: ' + str(crc)
                )

                if len(rec_list) < fragCount:
                    need_to_add = fragCount - len(rec_list)
                    rec_list.extend([''] * need_to_add)  # empty list for messages of size fragCount
                rec_list[fragIndex - 1] = data

                received_chunks += 1
                if received_chunks == fragCount:
                    break  # This is where the second while loop ends

Post a Comment for "Sending File Over UDP Divided Into Fragments"