Search code examples
c++dockersocketsboost

boost:asio::write writes to socket successfully, but server doesn't see the data


I've written a simple code sample that writes some data to the socket towards a simple TCP echo server. The data is written successfully to the socket (writtenBytes > 0), but the server doesn't respond that it has received the data. The application is run in a Docker devcontainer, and from the development container, I'm communicating with the tcp-server-echo container on the same network.

io_service ioservice;
tcp::socket tcp_socket{ioservice};

void TestTcpConnection() {
  boost::asio::ip::tcp::resolver nameResolver{ioservice};
  boost::asio::ip::tcp::resolver::query query{"tcp-server-echo", "9000"};
  boost::system::error_code ec{};
  auto iterator = nameResolver.resolve(query, ec);
  if (ec == 0) {
    boost::asio::ip::tcp::resolver::iterator end{};
    boost::asio::ip::tcp::endpoint endpoint = *iterator;
    tcp_socket.connect(endpoint, ec);
    if (ec == 0) {
      std::string str{"Hello world test"};
      while (tcp_socket.is_open()) {
        auto writtenBytes =
            boost::asio::write(tcp_socket, boost::asio::buffer(str));
        if (writtenBytes > 0) {
          // this line is executed successfully every time.
          // writtenBytes == 13, which equals to str.length()
          std::cout << "Bytes written successfully!\n";
        }
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(2000ms);
    }
  }
}

In this case writtenBytes > 0 is a sign of a successful write to the socket.

The echo server is based on istio/tcp-echo-server:1.2 image. I can ping it from my devcontainer by name or IP address with no issues. Also, when I write a similar code sample but using async functions (async_resolve, async_connect, except for the write operation, which is not async), and a separate thread to run ioservice, the server does see my data and responds appropriately.

Why the server doesn't see my data in case of no-async writes? Thanks in advance.


Solution

  • It turned out the issue was with the Docker container that received the message. The image istio/tcp-echo-server:1.2 doesn't write to logs unless you send the data with \n in the end.