Boost logo

Boost Users :

Subject: Re: [Boost-users] Modify an asio echo server so that it does not send message back to client
From: Gavin Lambert (gavinl_at_[hidden])
Date: 2015-06-10 20:16:06


On 11/06/2015 11:56, Nicholas Yue wrote:
> I now have a process() method with the bytes_transferred parameter.
>
> Newbie question, how do I know the last chunk has been sent, so
> that I can now process the data (which will be binary) ?
>
> Is there some simple example which illustrate this I can refer to ?

There isn't any inherent way to know. TCP is a stream protocol -- you
just receive a continuous stream of bytes with no demarcation of any kind.

You will need to define something at the application layer of the
protocol to decide when a logical unit is complete, typically either by
inserting some delimiter that you know can never occur mid-message or by
sending the length of the following data early on.

Note that ASIO does provide some helper methods for these scenarios --
instead of using async_read_some, which just returns data as it becomes
available, you can use asio::async_read (which you can tell to not
return until it has read a specific number of bytes) or
asio::async_read_until (read until a specific delimiter). (It's tricky,
though not impossible, to do a combination of the two -- but it's
something you should avoid if you have a choice.)

So for a line-based protocol you could async_read_until a CRLF (or just
LF, depending on the other end), or for a binary protocol that sends a
4-byte length followed by a payload you could async_read 4 bytes to get
the length, then async_read that many bytes to get the payload.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net