有没有一种方法可以从streambuf中读取字节而不必将其删除?
我正在从缓冲区中读取“消息大小”字段以检查是否接收到了整个消息。
如果没有,我会发起另一个异步读取以获取它,但是处理程序无法知道消息应该有多长 - 因为大小字段已被删除。
任何帮助都将不胜感激!
例如:
boost::asio::streambuf _buffer;
void onReceive(const boost::system::error_code& e, std::size_t bytesTransferred)
{
if(e) return;
if(_buffer.size() > 0)
{
// Partial message was previously received, but I don't know how long.
}
else
{
_buffer.commit(bytesTransferred);
/* Read the size (and remove it from the stream) */
unsigned short size = 0;
std::istream in(&_buffer);
in.read((char*)&size, sizeof(unsigned short);
/* Got the whole message? */
if(_buffer.size() > size)
{
/* Yes. */
}
else
{
/* No - read the rest. */
boost::asio::async_read(/*...*/);
}
}
}