使用 asio null_buffers 提升 asio udp 套接字

Rat*_*Dey 4 c++ boost udp boost-asio

我想使用 Boost ASIO 库异步接收来自 UDP 套接字的数据。我不想在使用 async_receive_from 接收数据时使用固定长度的缓冲区。

以下代码是我如何使用 boost asio::null_buffers 来确定传入的数据包大小并相应地创建缓冲区。

socket.async_receive_from(boost::asio::null_buffers(),
                           remote_endpoint,
                           [&](boost::system::error_code ec, std::size_t bytes) {
  unsigned int readbytes = socket.available();
  if (readbytes > buffer_size) {
    //reallocate buffer
  }
  std::size_t recvbytes = socket.receive_from(
      boost::asio::buffer(buffer, buffer_size), remote_endpoint, 0, error);
Run Code Online (Sandbox Code Playgroud)

一切都按预期工作,但是,我想知道 boost null_buffer 是否分配一个内部缓冲区来保留收到的 UDP 数据包的副本,并在调用 socket.receive_from() 时复制到给定的缓冲区。

另外我想知道在使用 UDP 套接字时使用 null_buffer 对性能和内存使用有什么影响。

seh*_*ehe 5

理查德霍奇斯所说的话。

此外,Boost 1.66.0 具有新的接口,其中null_buffers已过时,可以使用async_wait套接字上的操作完成反应器式的集成:

在此处输入图片说明

参见例如此处的文档https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/basic_socket/wait/overload1.html