C++ / ASIO / TCP / Socket / Response sometimes/often is empty even though do_write was called successfully

  asio, c++

I have a question regarding asio and TCP sockets.

Currently I am using async_read_until until there is a sequence of two "nn". If there is no error I do some database stuff and return a response to the client. This basically is done using the asio examples. My question is this: if I run into an error (asio::error_code& ec != null) then how can I make sure that I can write an answer back to the client? Because if I do call do_write(…) from within the error condition around half of my responses don’t reach the client.

void do_read (some data) {
asio::async_read_until(socket_, buf_, "nn",
            [this, self](const asio::error_code& ec, std::size_t bytes_transferred)
 {
  if(ec) {
    do_write("This answer does not reach the client 50% of the time, sometimes more; sometimes less");
  } else {
    do_write("You did well my young apprentice! Always works");
  }
 });
}

void do_write(const std::string& response) {
  asio::async_write(socket_, asio::buffer(response.c_str(), response.length()),
    [this, self, response](std::error_code ec, std::size_t bytes_transferred) {
      if (ec) {
        // no error here whats-o-ever!
      } else {
        // OK: bytes_transferred == response.size()
      }
    }
}

Surely I do something wrong here, but what? At first I thought this is all async so maybe the parameters went out of scope. But do_write is called regardless of ec == null and I even testet it using verbatim strings, like in this example.

  • Archlinux
  • ASIO 1.18.1
  • netcat as client
  • GCC 10.2.0
  • Not using boost

Source: Windows Questions C++

LEAVE A COMMENT