我正在尝试编写一个应用程序,该应用程序使用 Google 的 Protocol Buffer 通过 TCP 连接反序列化数据(使用 Protocol Buffer 从另一个应用程序发送)。问题是它看起来好像 Python 中的 Protocol Buffer 只能反序列化字符串中的数据。由于 TCP 没有明确定义的消息边界,并且我尝试接收的其中一条消息具有重复字段,因此在最终传递要反序列化的字符串之前,我不知道要尝试接收多少数据。
在 Python 中有什么好的做法吗?
最佳答案
不要只是将序列化的数据写入套接字。首先发送一个包含序列化对象长度的固定大小字段。
发送方大致是:
socket.write(struct.pack("H", len(data)) #send a two-byte size field
socket.write(data)
recv'ing 的一面变成这样:
dataToRead = struct.unpack("H", socket.read(2))[0]
data = socket.read(dataToRead)
这是套接字编程的常见设计模式。大多数设计都扩展了无线结构以包含一个类型字段,因此您的接收方会变成这样:
type = socket.read(1) # get the type of msg
dataToRead = struct.unpack("H", socket.read(2))[0] # get the len of the msg
data = socket.read(dataToRead) # read the msg
if TYPE_FOO == type:
handleFoo(data)
elif TYPE_BAR == type:
handleBar(data)
else:
raise UnknownTypeException(type)
您最终会得到如下所示的无线消息格式:
struct {
unsigned char type;
unsigned short length;
void *data;
}
这样可以合理地防止有线协议(protocol)在未来出现不可预见的要求。这是一个 Type-Length-Value协议(protocol),您会在网络协议(protocol)中一次又一次地找到它。
关于python - 如何使用 Python 和 Google 的 Protocol Buffer 来反序列化通过 TCP 发送的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2038083/