Python 套接字发送 Uint16 和 Uint32
Python Sockets send Uint16 and Uint32
我需要通过具有以下结构的 python 套接字发送请求:
{
Uint16 data_one
Uint16 data_one
Uint32 data_one
}
我的服务器和客户端都在工作,但我真的不知道如何编码和解码这种数据以通过套接字发送它。谢谢!
看看struct
module中的函数。使用 struct.pack
生成字节流并通过网络发送,然后在另一端使用 struct.unpack
解压数据:
# sender
buffer = struct.pack('!3H', *data)
# ... send it
# receiver
# ... get the buffer
data = struct.unpack('!3H', buffer)
考虑构建库: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
我需要通过具有以下结构的 python 套接字发送请求:
{
Uint16 data_one
Uint16 data_one
Uint32 data_one
}
我的服务器和客户端都在工作,但我真的不知道如何编码和解码这种数据以通过套接字发送它。谢谢!
看看struct
module中的函数。使用 struct.pack
生成字节流并通过网络发送,然后在另一端使用 struct.unpack
解压数据:
# sender
buffer = struct.pack('!3H', *data)
# ... send it
# receiver
# ... get the buffer
data = struct.unpack('!3H', buffer)
考虑构建库: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