boost::asio async_read 未接收数据或不使用回调
我正在尝试使用 boost asio 的 async_read()
免费函数从服务器应用程序接收数据,但我在接收时设置的回调从未被调用。
客户端代码是这样的:
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));
}
我尝试使用小数据(短字符串),但无法让它工作。当我使用两个相同的第一个参数的同步读取函数 (boost::asio::read()
) 时,一切工作正常。
我在使用 io_service 时遗漏了什么吗?我仍然不确定它是如何工作的。
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.
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.
Am I missing something with the use of the io_service? I am still unsure about how it works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
boost::asio::service::run ()
是一个阻塞调用。现在,在您的示例中,它可能会也可能不会立即返回。如果没有,您甚至在创建套接字之前就会被阻止,并且永远不会调用 read,因此不能期望回调。否则,调度循环将退出,因此不会传递任何回调。了解有关
boost 的更多信息::asio::service::run ()
。我建议您查看文档,包括教程、示例和参考。值得全面阅读它来理解这个概念。希望有帮助!
PS:顺便说一句,您的代码不是异常安全的。请注意,如果类的构造函数因异常而失败,则永远不会调用该类实例的析构函数。因此,如果 m_pSocket 的类型不是“智能指针”之一,则至少可能会泄漏。您应该考虑使其异常安全,将代码移至用户应调用的另一个方法,甚至用自由函数包装此功能。
boost::asio::service::run ()
is a blocking call. 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. Otherwise, dispatch loop is exited, so no callbacks are ever delivered.Read more about
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!
P.S.: On a side note, your code is not exception safe. 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". 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.