2

我正在使用 TCP 客户端/服务器将 Cap'n Proto 消息从 C++ 发送到 Java。

有时接收缓冲区可能会过满或过少,为了处理这些情况,我们需要知道消息的大小。

当我在 Java 中检查缓冲区的大小时,我得到 208 个字节,但是调用

MyModel.MyMessage.STRUCT_SIZE.total()

返回 4(不确定此处使用的计量单位)。

我注意到 4 分为 208、52 次。但我不知道使用 52 的重要转换因子。

如何检查 Java 中的消息大小?

4

1 回答 1

2

MyMessage.STRUCT_SIZE表示该结构本身的恒定大小(以 8 字节字为单位),但如果该结构包含非平凡字段(如 Text、Data、List 或其他结构),那么这些字段也会占用空间,以及空间量它们占用的空间不是恒定的(例如,文本将根据字符串的长度占用空间)。

一般来说,你应该尽量让 Cap'n Proto 直接写入/读取相应ByteChannel的 s,这样你就不必自己跟踪大小。但是,如果您确实必须提前计算消息的大小,则可以使用以下方法:

ByteBuffer[] segments = message.getSegmentsForOutput();
int total = (segments.length / 2 + 1) * 8;  // segment table
for (ByteBuffer segment: segments) {
  total += segment.remaining();
}
// now `total` is the total number of bytes that will be
// written when the message is serialized.

在 C++ 大小上,您可以使用capnp::computeSerializedSizeInWords()from serialize.h(并乘以 8)。

但同样,您确实应该通过使用org.capnproto.Serialize流式 I/O 的方法来构建您的代码以避免这种情况。

于 2015-08-15T23:06:35.740 回答