Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost asio udp socket using asio null_buffers

I want to receive data from an UDP socket asynchronously using Boost ASIO library. I don't want to use a fixed length buffer while receiving data using async_receive_from.

The following code is how I used boost asio::null_buffers to determine the incoming packet size and create buffer accordingly.

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);

Everything works as expected, however, I want to know if boost null_buffer allocates an internal buffer to keep a copy of the UDP packet received and copies to the given buffer when socket.receive_from() is called.

Also I want to know what is the impact of using null_buffer on performance and memory usage while using a UDP socket.

like image 294
Ratnadeep Dey Avatar asked Mar 06 '23 11:03

Ratnadeep Dey


2 Answers

What RichardHodges said.

In addition, Boost 1.66.0 has the new interface where null_buffers are obsolete and reactor-style integration can be dones using the async_wait operations on your socket:

enter image description here

See e.g. the docs here https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/basic_socket/wait/overload1.html

like image 132
sehe Avatar answered Mar 20 '23 21:03

sehe


null_buffers is not a buffer. It's a value of a type used to select a different (and special) overload of the receive/read/write functions.

These overloads simply test the state of the socket in order to tell you whether there is data to read (and how much of it there is).

Your approach is fine and it is efficient.

like image 26
Richard Hodges Avatar answered Mar 20 '23 20:03

Richard Hodges