boost::asio::async_write 和 std::string

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

所以我的设置如下:

通信工作正常,我应该能够发送对客户端请求的答复。为此,我使用了以下代码:

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;

问题是消息打印得很好,但随后它跳转到最后一次打印而没有将消息发送给客户端,因此客户端阻塞。

服务器中的输出如下:

I2C message from Arduino: l 1 14.88
Passei o async_write

如果我发送这样一条通用消息:

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

客户端按预期收到消息。

我很确定问题与我将字符串转换为 char* 的方式有关,但我没有找到使其工作的方法。

sizeof(I2CrxBuf_.c_str()) 是错误的。另外,您可以直接执行 buffer(I2CrxBuf) 。有关其他重载,请参阅 docs

除此之外,意识到字符串 需要 保持活动状态直到异步操作结束(并且不能在与此同时)。

文档中的所有示例都对如何实现这一点有很好的想法。