【发布时间】:2017-12-09 17:51:05
【问题描述】:
所以我的设置如下:
- Raspberry Pi 作为 TCP 服务器使用 boost asio c++ 库;
- 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 recevied\n" ), boost::bind(&conn::h_write, shared_from_this()));
客户端按预期收到消息。
我很确定问题与我将字符串转换为 char* 的方式有关,但我没有找到让它工作的方法。
【问题讨论】:
-
sizeof(I2CrxBuf_.c_str())是 4 个字节。我想你的意思是I2CrxBuf_.size()。 -
谢谢,那是真的,但仍然没有发送...
-
我也检查过 c.str() 方法没有从字符串末尾删除 '\n '。由于客户端需要消息才能拥有它,这应该不是问题。
-
不太确定我是否理解问题,但是......从
std::string::c_str返回的值应该被视为临时值,因此不适合传递给异步函数,例如async_write。如果I2CrxBuf_在范围内并且在写入操作期间未修改,则只需使用它构造缓冲区--boost::asio::buffer(I2CrxBuf_)。 -
抱歉@arrowd 这确实是问题所在。
标签: c++ multithreading boost-asio tcpserver condition-variable