Search code examples
socketsboostboost-asio

What is the use of boost::asio::async_write function


Can anyone please help me with this code , what is the use of "boost::asio::async_write" function here

Does it sends acknowledgment back to the client ?

 void handle_read(const boost::system::error_code& error,
          size_t bytes_transferred)
      {
        if (!error)
        {
          boost::asio::async_write(socket_,
              boost::asio::buffer(data_, bytes_transferred),
              boost::bind(&session::handle_write, this,
                boost::asio::placeholders::error));
        }
        else
        {
          delete this;
        }
      }

Solution

  • It looks like this is from an "echo server" example. async_write writes the contents of boost::asio::buffer(data_, bytes_transferred) to the socket.

    Since we're inside handle_read we can guess that this function itself is the completion handler for a likely async_read call that filled that data_ buffer. Since we use the exact number of bytes reported back by async_read (bytes_transferred) and there's no visible manipulation on data_, we can assume that this simply sends the exact message (or data in general) received to socket_. If socket_ was also the endpoint in the async_read this is the definition of an echo server.