我正在尝试使用 MessagePack 序列化 Delphi 中的记录,然后使用 ZeroMQ TCP 协议将其发送到 Python 服务器。
b'\xa8DataType\x01\xa4data\xbf{"major":1,"minor":0,"build":2}\x00'
我在服务器端反序列化它时遇到问题。任何想法为什么会发生这种情况?是某种编码问题吗?谢谢!
更新#1:
我使用 www.msgpack.org 上推荐的消息包库“QMsgPack”这是一些 Delphi 代码。我的用户定义记录和枚举:
Version = Record
major : Integer;
minor : Integer;
build : Integer;
end;
TDataType = (dtUnset, dtVersion, dtEntityDescription, dtEntityDescriptionVector, dtEntityState, dtEntityStateVector, dtCommandContinue, dtCommandComplete);
TPacket = Record
DataType : TDataType;
data : string;
end;
以及序列化对象的代码:
begin
dmVersion.major := 1;
dmVersion.minor := 1;
dmVersion.build := 1;
lvMsg := TQMsgPack.Create;
lvMsg.FromRecord(dmVersion);
lvMsgString := lvMsg.ToString();
packet.DataType := dtVersion;
packet.data := lvMsgString;
lvMsg.Clear;
lvMsg.FromRecord(packet);
lvbytes:=lvMsg.Encode;
ZeroMQ.zSendByteArray(skt, lvbytes);
然后我尝试在 python 服务器中反序列化接收到的字节数组,如下所示:
b'\xa8DataType\x01\xa4data\xbf{"major":1,"minor":0,"build":2}\x00'
通过使用umsgpack.unpack()然后在结果中打印出结果,如下所示:
packet_packed = command.recv()
# Unpack the packet
umsgpack.compatibility = True
packet = umsgpack.unpackb( packet_packed )
print (packet)
for item in packet:
print (item)
这就是我在屏幕上打印出来的:
b'DataType'
68
97
116
97
84
121
112
101
我希望这有帮助!谢谢!
更新#2
这是python端的一些服务器代码。VDS_PACKET_VERSION 是一个常量 int,设置为 1。
# Make sure its a version packet
if VDS_PACKET_VERSION == packet[0]:
# Unpack the data portion of the packet
version = umsgpack.unpackb( packet[1] )
roster = []
if ( VDS_VERSION_MAJOR == version[0] ) and ( VDS_VERSION_MINOR == version[1] ) and ( VDS_VERSION_BUILD == version[2] ):
dostuff()
使用当前的序列化对象
b'\x82\xa8DataType\x01\xa4data\xbf{"major":1,"minor":1,"build":1}'
我明白了
KeyError: 0 on packet[0]
这是为什么?