Search code examples
pythonsocketsstructserverclient

Wrong unpacking of message from server. Python. Sockets


I want to pack some information and send it from server to client. Then client must correctly unpack message. Server send type of sensor (string), name of channel (string) and photo (bytes). I did it. I use length of channel and length of photo because their size can change.

msg = struct.pack('>3sHI', sensor, len(channel), len(photo)) + channel + photo

For clien I have it.

def recv_packets(connection, n):
    piece = b''
    while len(piece) < n:
        packet = connection.recv(n - len(piece))
        if not packet:
            return None
        piece += packet
    return piece


def my_recv(connection):

    sensor = recv_packets(connection, 3)
    if not sensor:
        print("not sensor")
        return None

    sensor_type = struct.unpack('>3s', sensor)[0]


    length_of_channel_name = recv_packets(connection, 2)
    if not length_of_channel_name:
        print("not length of channel name")

        # return None
    else:
        channel_len = struct.unpack('>H', length_of_channel_name)[0]

        # here we must get channel name "ChannelFirst", but we also got ff at start. 
        # ("ffChannelFirst")
        # it isn't right

        channel_name = recv_packets(connection, channel_len + len(sensor) + 1)
        print(channel_name.decode('utf-8'))
        
        #the same code for photo
    
    return photo, channel_name, sensor_type

As you see I can get correct channel name. (I always get ff for start). Then I can't correctly get a photo. And I don't understand whats wrong. Help me, please.


Solution

  • This string doesn't work.

    msg = struct.pack('>3sHI', sensor, len(channel), len(photo)) + channel + photo

    I did so. An now all is ok.

        msg = struct.pack('>3sH', sensor, len(channel)) + channel
        msg += struct.pack('>I', len(photo)) + photo