Is there a way to read from a streambuf without removing the bytes?
I’m reading a ‘message size’ field from the buffer to check if the whole message was received.
If not, I’m posting another async read to get it, but the handler then has no way to know how long the message was supposed to be – because the size field was removed.
Any help appreciated!
E.g.
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(/*...*/);
}
}
}
You can use read_async to initiate a read using the size of the message header and then adjust it in a ‘completion condition’ callback, like so:
EDIT: Added typedef for error_code.