boost::asio 如何以正确的方式读取完整的缓冲区?

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

我正在学习 boost::asio,现在对读取完整缓冲区的正确方法感到困惑。例如,当建立连接时,我想用下一种方式读取 uint32_t

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

如您所见,我设置了缓冲区大小。在其他情况下,我在 read_some 数据上收到了长度为 len 的数据。

所以主要问题是:如果我在调用 buffer 时设置了所需的缓冲区长度,boost::asio 是否保证会读取 uint32_t 的所有 4 个字节?

或者如果不能保证 - 我如何才能读取完整的缓冲区? (所有 4 个字节)

来自 read_some 参考:

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.

附备注:

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.

因此,您要么必须循环调用 read_some,要么只调用 read,这将:

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.

在您的情况下 read 的用法是:

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