Search code examples
c++multithreadingboost-asiotcpservercondition-variable

boost::asio::async_write with std::string


So my setup is the following:

  • Raspberry Pi working as a TCP server with boost asio c++ library;
  • TCP Client running on other machine;

The communication is working fine expect for the part that I should be able to send an answer to the client request. To do so I'm using the following code:

std::cout << "\tI2C message from Arduino: " << I2CrxBuf_;
boost::asio::async_write(sock_, boost::asio::buffer( I2CrxBuf_.c_str(), sizeof(I2CrxBuf_.c_str()) ), boost::bind(&conn::h_write, shared_from_this()));
std::cout << "Passei o async_write" << std::endl;

The thing is that the message prints just fine but then it jumps to the last print without sending the message to the client, and so the client blocks.

The output in the server is the following:

I2C message from Arduino: l 1 14.88
Passei o async_write

If I send a generic message like this:

boost::asio::async_write(sock_, boost::asio::buffer( "Message recevied\n" ), boost::bind(&conn::h_write, shared_from_this()));

The client receives the message as it was expected.

I'm pretty sure the problem as to do with the way I'm converting the string to char*, but I not finding a way to make it work.


Solution

  • sizeof(I2CrxBuf_.c_str()) is wrong. Also, you can do buffer(I2CrxBuf) directly. See docs for other overloads.

    Other than that, realize that the string needs to stay alive until the end of the async operation (and cannot be modified in the mean time).

    All the samples in the documentation have good ideas on how to achieve this.