1

I am using async_read with streambuf. However, I would like to limit the amount of data read to 4, so I can properly handle header before going to body.

How can I do that using async_read?

Sam Miller
  • 23,808
  • 4
  • 67
  • 87
Vladimir
  • 191
  • 1
  • 9

3 Answers3

5

Use two async_read operations where the first reads a 4 byte header, and the second reads the message body. Your handler to the first async_read should start the async_read for the message body.

The asio examples use this technique in a couple of places, the serialization example is one. I also answered a similar question, though it uses synchronous reads, but the concept is the same.

Community
  • 1
  • 1
Sam Miller
  • 23,808
  • 4
  • 67
  • 87
1

You can guarantee the header is available using transfer_at_least as CompletionCondition on async_read.

Any superfluous body data (or further headers) can be processed once you handle the initial header.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
0
boost::asio::transfer_exactly(streambuf.size()) 

is what you need.just try using like this:

boost::asio::async_read(socket_, 
                        buf,boost::asio::transfer_exactly(size_),
                        boost::bind(callback,
                        boost::asio::placeholders::error));
smali
  • 4,687
  • 7
  • 38
  • 60
f_x_p
  • 58
  • 9