gpt4 book ai didi

java - Protobuf c# 到 java 反序列化多条消息

转载 作者:搜寻专家 更新时间:2023-10-31 20:29:04 29 4
gpt4 key购买 nike

我正在尝试解析在 vb.net 中生成的 java 中的多个 Protocol Buffer 消息

我正在使用优秀的 protobuf-net 将多条消息流式传输到 java,如下所示:

ProtoBuf.Serializer.SerializeWithLengthPrefix(Of Msg)(postStream, msg, 
ProtoBuf.PrefixStyle.Base128)

在 Java 中,我使用以下代码来解析消息

final byte[] buffer = new byte[4096];
for (int c = ins.read(buffer); c >= 0; c = ins.read(buffer)) {
Msg msg = Msg.parseDelimitedFrom(new ByteArrayInputStream(buffer));
}

问题是在解析第一条消息后,第二次解析时抛出错误并出现以下错误:

com.google.protobuf.InvalidProtocolBufferException: While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either than the input has been truncated or that an embedded message misreported its own length.

缓冲区大小和消息大小应该相同吗?如果是,那么我应该如何解析它,尤其是对于大消息。

最佳答案

问题是你需要直接从原始流中读取,而不是一次读取一个 block 。 (即使你知道每条消息正好是 4096 字节,你也不能确定一次阅读那么多)我建议你使用

while(stream still open) {
Msg msg = Msg.parseDelimitedFrom(ins);
}

注意:TCP 是流协议(protocol),不是消息协议(protocol)。您只能保证一次读取一个字节,您获得的任何额外字节都是奖励。

关于java - Protobuf c# 到 java 反序列化多条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887350/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com