Boost logo

Boost Users :

Subject: Re: [Boost-users] Using boost::asio
From: Andrew Holden (aholden_at_[hidden])
Date: 2011-06-02 13:51:16


On Thursday, June 02, 2011 12:27 PM, Ram Sundar wrote:
> I am trying to use boost::asio for a project where we
> currently use ACE. The way it currently works, the
> data that is passed between the server and client is
> preceded by a header with the data length. Currently
> with ACE when data is ready to be read at the socket,
> the handler function is invoked, and we invoke a ioctl
> with FIONREAD to read the number of bytes ready to be
> read and then allocate a buffer of that length to read
> the data. The reason we do this way is because the data
> may be sent in chunks. Internally we keep track of how
> much data we have received etc. I am at a loss to know
> how to do this using boost::asio. All the read methods
> expect a buffer where data will be read and it also
> needs the size of the buffer. Is there a way we get
> notified when data is ready to be read, and do similar
> operation. ie read the number of bytes available to
> read and then allocate buffers to read the data? Are
> there any other methods to accomplish the same?

There should be no reason to worry about whatever chunks TCP creates when it sends data. Try the following method:

1: Allocate a buffer just big enough for the header.
2: Call async_read to read the header. In the ReadHandler:
2a: Check for errors
2b: Extract the data length from the header.
2c: Allocate a buffer of exactly that size.
2d: Call async_read to read the data. In the ReadHandler:
2d1: Check for read errors.
2d2: Process the data knowing that you have the whole message.
2d3: Allocate a buffer for the next header (or reuse the existing header buffer) and call async_read with the same ReadHandler as described in step 2.


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