我有一些代码试图从Java套接字中读取Google Protocol Buffer消息。但是,如果mergeDelimitedFrom()方法读入无效数据或套接字连接已重置(可能还有其他原因),则可能会引发IOException。如果连接重置,我想退出循环,但如果这只是一个无效的消息,我想继续运行。一个想法是在X连续失败后只需要有某种异常计数器并退出,但我希望能够找出发生的错误类型,而不是在黑暗中。处理来自Google协议缓冲区库的IOExceptions
这基本上是我的代码:
while (m_Running)
{
SomeMessage message = null;
try
{
final Builder builder = SomeMessage.newBuilder();
if (builder.mergeDelimitedFrom(m_InputStream))
{
message = builder.build();
}
else
{
// Google protocol buffers doesn't document it very well
// but if mergeDelimietedFrom returns false then it has
// reached the end of the input stream. For a socket, no
// more data will be coming so exit from the thread
m_Running = false;
}
}
catch (final IOException e)
{
// what should really be done here ???
}
}
我想通过使用mergeDelimitedFrom而不是mergeFrom来选择成帧协议,因为协议缓冲库负责八位字节计数。让我想知道为什么他们提供这种方法,如果不实用的话。我想我可以通过直接从流中读取数据并将字节数组传递给协议缓冲区库来重复同样的逻辑,但是这看起来好像重新发明了一下轮子。 –