[英]boost::asio async_read doesn't receive data or doesn't use callback
I am trying to receive data from a server application using boost asio's async_read()
free function, but the callback I set for when the receiving is never called. 我正在尝试使用boost asio的async_read()
免费函数从服务器应用程序接收数据,但是我从未设置为接收时设置的回调。
The client code is like this: 客户端代码是这样的:
Client::Client()
{
m_oIoService.run(); // member boost::asio::io_service
m_pSocket = new boost::asio::ip::tcp::socket(m_oIoService);
// Connection to the server
[...]
// First read
boost::asio::async_read(*m_pSocket,
boost::asio::buffer((void*)&m_oData, sizeof(m_oData)),
boost::bind(&Client::handleReceivedData, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
I tried with small data (a short string) and I can't get it to work. 我尝试使用小数据(短字符串),但无法正常工作。 When I use the synchronous read function ( boost::asio::read()
) using the two same first parameters, everything works perfectly. 当我使用两个相同的第一个参数使用同步读取功能( boost::asio::read()
)时,一切工作正常。
Am I missing something with the use of the io_service? 使用io_service是否会丢失某些内容? I am still unsure about how it works. 我仍然不确定它是如何工作的。
boost::asio::service::run ()
is a blocking call. boost::asio::service::run ()
是阻塞调用。 Now, in your example it may or may not return immediately. 现在,在您的示例中,它可能会立即返回,也可能不会立即返回。 In case it doesn't, you you are blocked even before you create a socket, and never call read, so cannot expect a callback. 如果没有,您甚至会在创建套接字之前就被阻塞,并且从不调用read,因此不能期望回调。 Otherwise, dispatch loop is exited, so no callbacks are ever delivered. 否则,将退出调度循环,因此不会传递任何回调。
Read more about boost::asio::service::run ()
. 阅读有关boost::asio::service::run ()
。 I recommend you check out documentation including tutorial, examples and reference. 我建议您查看文档,包括教程,示例和参考。 It is worth going trough it in full to understand the concept. 值得深入了解它的概念。
Hope it helps! 希望能帮助到你!
PS: On a side note, your code is not exception safe. PS:顺便说一句,您的代码不是异常安全的。 Beware that if constructor of the class fails with exception then destructor of that class instance is never called. 注意,如果类的构造函数因异常而失败,则永远不会调用该类实例的析构函数。 Thus, you may leak at least m_pSocket
if its type is not one of the "smart pointers". 因此,如果m_pSocket
的类型不是“智能指针”之一,则可能会泄漏至少。 You should consider making it exception safe, moving the code to another method that should be called by user, or even wrapping this functionality with a free function. 您应该考虑使其异常安全,将代码移至用户应调用的另一种方法,甚至将此功能与自由函数包装在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.