0

我需要通过具有以下结构的 python 套接字发送请求:

{
   Uint16 data_one
   Uint16 data_one
   Uint32 data_one
}

我的服务器和客户端都在工作,但我真的不知道如何编码和解码这种数据以通过套接字发送它。谢谢!

4

2 回答 2

1

看看struct模块中的功能。用于struct.pack生成字节流并通过线路发送,然后struct.unpack在另一端用于解包数据:

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


# receiver
# ... get the buffer
data = struct.unpack('!3H', buffer)
于 2020-11-25T13:50:24.620 回答
0

考虑 Construct 库:https ://construct.readthedocs.io/en/latest/

与 Protobuf 类似但不同的是,它允许您定义“打包”数据格式,这在处理打包数据格式(例如网络数据包或专有数据格式)时非常理想。

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)

输出:

Serialised Bytes: 007b0141000003e7

Deserialised object:
Container: 
    field1 = 123
    field2 = 321
    field3 = 999
于 2020-11-25T14:05:06.783 回答