Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::asio how to read full buffer in right way?

I am learning the boost::asio and now confusing about the right way to read the full buffer. For example, when connection established I want to read uint32_t in next way:

std::uint32_t size;
size_t len = m_socket.read_some(buffer(&size, sizeof(std::uint32_t)));

As you see I set up the buffer size. In other case I received the len with length on read_some data.

So the main question: is the boost::asio guarantied that there are would be read all 4 bytes of uint32_t if I set up the needed buffer length when call buffer?

Or if it not guaranteed - how I can read full buffer? (all 4 bytes)

like image 586
AeroSun Avatar asked Feb 13 '15 22:02

AeroSun


1 Answers

From the read_some reference:

This function is used to read data from the stream socket. The function call will block until one or more bytes of data has been read successfully, or until an error occurs.

With remarks:

The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.

So either you'll have to call read_some in a loop, or just call read, which will:

block until one of the following conditions is true:

  • The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.
  • An error occurred.

This operation is implemented in terms of zero or more calls to the stream's read_some function.

The usage of read in your case would be:

std::uint32_t size;
size_t len = read(m_socket, buffer(&size, sizeof(std::uint32_t)));
like image 93
Barry Avatar answered Oct 24 '22 03:10

Barry