Python Sockets send Uint16 and Uint32

715 views Asked by At

I need to send a request via a python socket with the following structure:

{
   Uint16 data_one
   Uint16 data_one
   Uint32 data_one
}

I have my server and client working, but i do not really know how can i encode and decode this kind of data to send it over the socket. Thanks!

2

There are 2 answers

0
Jan Christoph Terasa On BEST ANSWER

Take a look at the functions in the struct module. Use struct.pack to generate the bytestream and send it over the wire, then use struct.unpack on the other end to unpack the data:

# sender
buffer = struct.pack('!3H', *data)
# ... send it


# receiver
# ... get the buffer
data = struct.unpack('!3H', buffer)
0
Alastair McCormack On

Consider the Construct library: https://construct.readthedocs.io/en/latest/

Similar but different to Protobuf, it allows you to define a "packed" data format, which is ideal when dealing with packed data formats, such as network packets or proprietary data formats.

from construct import Struct, Int16ub, Int32ub

# Your data format
my_packet_struct = Struct(
    "field1" / Int16ub,
    "field2" / Int16ub,
    "field3" / Int32ub
)

# Some data you want serialise.
# The dict keys need to match those in the packet format above,
# but not necessarily the same order
my_data = {
    "field2": 321,
    "field1": 123,
    "field3": 999
}

# Serialise your data to bytes
my_serialised_bytes = my_packet_struct.build(my_data)
print("Serialised Bytes: {}".format(my_serialised_bytes.hex()))
# Send the data: socket.write(my_serialised_bytes)

# Deserialise to prove it works properly
my_deserialised_bytes = my_packet_struct.parse(my_serialised_bytes)

print("\nDeserialised object:")
print(my_deserialised_bytes)

Output:

Serialised Bytes: 007b0141000003e7

Deserialised object:
Container: 
    field1 = 123
    field2 = 321
    field3 = 999