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

标签 c++ boost boost-asio

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

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

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

所以主要问题是: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)));

关于c++ - boost::asio 如何以正确的方式读取完整缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28509796/

相关文章:

除非包含 endl,否则 C++ 重载的 << 运算符无法正确输出

python - 在 C++ 中运行 python

c++ - boost 'release' 上的 ptr_container 泄漏?

c++ - 系统的boost::asio无限循环:第一次连接后出现9错误

c++ - 不编译所有数据

C++ 转换为更精确的类型并失去准确性?

c++ - 如何静态检查两个比率是否相等?

c++ - boost::asio 的段错误,带有 deadline_timer 的异步 udp-server

boost - 关闭带有挂起连接的 boost::asio::ip::tcp::socket

c++ - {} vs. () 类成员的初始化