Reputation: 629
I have some client asio code that uses read_some()
until the number of bytes has been read. But from looking at all the examples, I can't figure out how to assemble the read buffer into a larger one that contains the entire message. How do I do this?
boost::array<char, 4096> buf;
while (lnTotalBytesRead < BigMessageSize)
{
size_t len = obj->socket_.read_some(boost::asio::buffer(buf), error);
lnTotalBytesRead += len;
// Need to append each received block into large block.
}
Upvotes: 1
Views: 2345
Reputation: 24164
I can't figure out how to assemble the read buffer into a larger one that contains the entire message. How do I do this?
Use a streambuf
instead of a boost::array
for your buffer. Though, as Andy said you really should be using read()
. As the documentation states, it is a composed operation and handles invoking read_some()
for you.
This operation is implemented in terms of zero or more calls to the stream's read_some function.
Upvotes: 0
Reputation: 26943
Andy's answer seems to me the recommended approach if you aren't really expecting messages to be too long
Usually you'll have to append your message until you have a unit of work upon which you can proceed to do something - this hints strongly that you need some marker structure in your messages (headers, body, etc.) so you can isolate individual messages from it.
The simplest marker structure you can do is a 4-byte word at the start of the each message stating the length of the message. Then you'll have to append with read_some
and check when the message full length has been received before dispatching it to further processing
Upvotes: 0
Reputation: 16256
Don't read_some
, read the whole buffer at once by read:
boost::array<char, BigMessageSize> buf;
boost::asio::read(obj->socket_, boost::asio::buffer(buf), error);
Upvotes: 2