我不能完全确定我是否正确地这样做了。如果同时尝试了Merge和ParseFromCodedStream。代码和输出如下:
bool tcp_connection::readDelimitedFrom(
google::protobuf::io::ZeroCopyInputStream* rawInput,
jvm* message, uint32_t* payloadSize) {
DEBUG && (cerr << "------ readDelimitedFrom.begin " << '\n');
// We create a new coded stream for each message. Don't worry, this is fast,
// and it makes sure the 64MB total size limit is imposed per-message rather
// than on the whole stream. (See the CodedInputStream interface for more
// info on this limit.)
google::protobuf::io::CodedInputStream input(rawInput);
// Read the size.
if (!input.ReadLittleEndian32(payloadSize)) return false;
DEBUG && (cerr << "------ readDelimitedFrom got size: " << *payloadSize << '\n');
DEBUG && (cerr << "------ input.CurrentPosition: " << input.CurrentPosition() << '\n');
DEBUG && (cerr << "------ " << '\n');
try {
google::protobuf::io::CodedInputStream::Limit limit =
input.PushLimit(*payloadSize);
DEBUG && (cerr << "------ PushLimit:" << *payloadSize << '\n');
// Parse the message.
if (!message->ParseFromCodedStream(&input)) return false;
DEBUG && (cerr << "------ MergeFromCodedStream" << '\n');
cout << "----------- size:" << message->ByteSize() << endl;
if (!input.ConsumedEntireMessage()) return false;
DEBUG && (cerr << "------ ConsumedEntireMessage" << '\n');
// Release the limit.
input.PopLimit(limit);
DEBUG && (cerr << "------ PopLimit" << '\n');
}
catch (const std::exception &exc)
{
// catch anything thrown within try block that derives from std::exception
cerr << exc.what() << endl;
return false;
}
// Tell the stream not to read beyond that size.
DEBUG && (cerr << "------ readDelimitedFrom return true " << '\n');
return true;
}
控制台输出:
---- connection.start (disabling Nagle)
------ h.r.h 4 bytes
------ readDelimitedFrom.begin
------ readDelimitedFrom got size: 76
------ input.CurrentPosition: 4
------
------ PushLimit:76
------ MergeFromCodedStream
----------- size:0
------ ConsumedEntireMessage
------ PopLimit
------ readDelimitedFrom return true
答案 0 :(得分:0)
我认为问题是我在解析标题后没有调整流。现在我只看了套接字头:
char buf[HEADER_SIZE];
socket().receive(boost::asio::buffer(buf), tcp::socket::message_peek);
对于想要了解正确代码的人:
ArrayInputStream ais(&m_readbuf[HEADER_SIZE], msg_len - HEADER_SIZE);
CodedInputStream cis(&ais);
jvm jvm;
bool isParsed = jvm.ParseFromCodedStream(&cis);
if (isParsed) {
DEBUG && (cerr << "jvm:[" << jvm.name() << "] size:" << jvm.ByteSize() << endl);
DEBUG && (cerr << "Got body:\n");
DEBUG && (cerr << show_hex(m_readbuf) << endl);
handle_request(&jvm);
}
else {
DEBUG && (cerr << "didnt parse <----\n");
}