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

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

本文关键字:with std string write asio async boost      更新时间:2023-10-16

,所以我的设置如下:

  • Raspberry Pi用Boost ASIO C 库充当TCP服务器;
  • 在其他计算机上运行的TCP客户端;

通信对我应该能够向客户请求发送答案的部分良好期望。为此,我正在使用以下代码:

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 receviedn" ), boost::bind(&conn::h_write, shared_from_this()));

客户会按预期收到消息。

我很确定要解决字符串转换为char*的问题,但是我没有找到使它起作用的方法。

sizeof(I2CrxBuf_.c_str())是错误的。另外,您可以直接执行buffer(I2CrxBuf)。请参阅文档以获取其他过载。

除此之外,还要意识到字符串需要才能保持活力,直到异步操作结束(并且不能在此期间修改)。

文档中的所有样本都对如何实现这一目标有好主意。