閱讀protobuf的消息時,我使用protobuf的現在幾個星期,但我仍然保持在解析protobuf的消息時的Java越來越例外。異常在Java中
我用C++創建我的protobuf消息和升壓插座將其發送到服務器套接字Java客戶端IST聽那裏。 C++的發送消息的代碼是這樣的:
boost::asio::streambuf b;
std::ostream os(&b);
ZeroCopyOutputStream *raw_output = new OstreamOutputStream(&os);
CodedOutputStream *coded_output = new CodedOutputStream(raw_output);
coded_output->WriteVarint32(agentMessage.ByteSize());
agentMessage.SerializeToCodedStream(coded_output);
delete coded_output;
delete raw_output;
boost::system::error_code ignored_error;
boost::asio::async_write(socket, b.data(), boost::bind(
&MessageService::handle_write, this,
boost::asio::placeholders::error));
正如你可以看到我寫的與WriteVarint32
消息的長度,因此Java端應通過使用parseDelimitedFrom
知道它應該有多遠閱讀:
AgentMessage agentMessage = AgentMessageProtos.AgentMessage
.parseDelimitedFrom(socket.getInputStream());
但它沒有幫助,我不斷收到這些類型的異常:
Protocol message contained an invalid tag (zero).
Message missing required fields: ...
Protocol message tag had invalid wire type.
Protocol message end-group tag did not match expected tag.
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.
這是重要要知道,這些例外情況不會引發每條消息。這只是我收到最多工作的信息的一小部分 - 我仍然想解決這個問題,因爲我不想忽略這些信息。
如果有人能夠幫助我或花費他的想法,我會非常感激。
另一個有趣的事實是我收到的消息數量。我的程序通常在2秒內發出1.000條消息。在20秒內約100.000等。我減少了人爲發送的消息,並且只傳輸6-8條消息,根本沒有錯誤。那麼這可能是Java客戶端套接字端的緩衝問題嗎?
對,假設有60.000條消息,其中5條平均損壞。
也許是一個愚蠢的問題,但有沒有什麼辦法可以在數據中留下填充/超大緩衝區,而不是修剪任何剩餘? –
(這個錯誤肯定可以很容易地由空閒零引起) –
@ Marc-Gravell:什麼是超大緩衝區?其實我不明白你認爲會導致這種情況。也許你可以指出我應該在哪裏尋找這個?順便說一句。我添加了一些其他的例外,我也收到。 –