【发布时间】:2017-11-12 21:19:52
【问题描述】:
我正在学习 Boost.Asio。我创建了一个简单的程序来将主机名解析为 IP 地址。使用同步解析操作时它工作正常。但是,当我尝试异步方式时,出现了一些奇怪的行为。
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
using boost::asio::ip::tcp;
void resolver_handler(
const boost::system::error_code& err,
tcp::resolver::iterator it
) {
if (err) {
std::cerr << "Resolver error: " << err.message() << std::endl;
return;
}
tcp::resolver::iterator end;
while (it != end) {
std::cout << "Host name: " << it->host_name() << std::endl;
std::cout << "Endpoint: " << it->endpoint() << std::endl;
std::cout << "Service name: " << it->service_name() << std::endl;
++it;
}
}
void resolve_host(boost::asio::io_service& io_service) {
tcp::resolver::query query("www.google.com", "http");
tcp::resolver resolver(io_service);
resolver.async_resolve(
query,
boost::bind(
resolver_handler,
boost::asio::placeholders::error,
boost::asio::placeholders::iterator
)
);
std::cout << "Bind" << std::endl; // <<<----This line
}
int main(int argc, char **argv) {
try {
boost::asio::io_service io_service;
resolve_host(io_service);
io_service.run();
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
当resolve_host函数的最后一行被注释掉时,报告
Resolver error: The I/O operation has been aborted because of either a thread exit or an application request
当该行存在时,它会给出正确的输出
Bind
Host name: www.google.com
Endpoint: 216.58.219.4:80
Service name: http
我所做的是打印出一些东西。我尝试在async_resolve 调用之后添加一些更简单的逻辑(例如int a = 1;),但它不起作用。在我看来,这是一个时间问题。也许有些东西退出得太快了。
我搜索此错误消息,但发现大多数帖子都是关于 C# 的。我相信这个错误消息不是来自 Boost 而是来自 Windows 系统。
谁能向我解释为什么会发生这种情况?非常感谢。
【问题讨论】:
-
当
resolve_host返回时,tcp::resolver不再存在,因为您在被销毁的堆栈上创建了它。它应该如何异步执行查询?某些东西必须拥有该解析器。有很多选择,但总得做点什么。 -
@DavidSchwartz 啊哈,没错。谢谢。
标签: c++ boost boost-asio asio