我正在使用Boost Asio进行跨平台网络。我尝试了各种连接方法,当尝试连接到Android上的套接字时,我不断收到“未找到元素”asio.misc错误。我很困惑,因为这是在成功解析域名后发生的。例如,如果我输入google.com作为主机和端口80,那么解析器将打印出所有20多个谷歌服务器,但之后它将不会连接说asio.misc“未找到元素”
这是我的代码:
boost::asio::io_service service;
boost::system::error_code ec;
boost::asio::ip::tcp::resolver resolver(service);
boost::asio::ip::tcp::resolver::query query(host, port);
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query, ec);
boost::asio::ip::tcp::resolver::iterator iterEnd;
boost::asio::ip::tcp::endpoint ep;
int it = 0;
while(iter != iterEnd)
{
ep = *iter++;
debug+="\nLooking at resolve with address " + ep.address().to_string();
it++;
}
//Try to connect through asio
boost::asio::ip::tcp::socket sock( service );
//asio::connect does all the iterator work for us.
boost::asio::connect(sock, iter, ec);
if( ec )
{
return new string("Should be connected but I can't");
}
else
{
debug+= "\n " + ec.message() + "\n " + ec.category().name();
return debug;
}
答案 0 :(得分:3)
调试循环耗尽了迭代器,导致使用结束迭代器调用boost::asio::connect()
。
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query, ec);
while(iter != iterEnd) // iterate to exhaustion
{
ep = *iter++;
// ...
}
// ...
boost::asio::connect(sock, iter, ec); // use exhausted iterator
要解决此问题,请考虑通过更改以下内容来构建调试信息时迭代iter
的副本:
while(iter != iterEnd)
{
ep = *iter++;
// ...
}
为:
for(tcp::resolver::iterator i = iter, end; i != end; ++i)
{
ep = *i;
// ...
}
这是一个完整的示例,大致基于原始代码,演示了差异:
#include <iostream>
#include <boost/asio.hpp>
void connect(const char* address, const char* port, bool exhaust)
{
using boost::asio::ip::tcp;
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::iterator iterator = resolver.resolve(
tcp::resolver::query(address, port));
// If flag is set, exhaust the iterator.
if (exhaust)
{
std::cout << "Exhausting iterator" << std::endl;
for (tcp::resolver::iterator end; iterator != end; ++iterator) {}
}
// Otherwise, exhaust a copy of the iterator.
else
{
std::cout << "Exhausting copy of iterator" << std::endl;
for (tcp::resolver::iterator i = iterator, end; i != end; ++i) {}
}
tcp::socket socket(io_service);
boost::system::error_code error;
connect(socket, iterator, error);
std::cout << error.category().name() << " -- "
<< error.message() << std::endl;
}
int main()
{
connect("google.com", "80", true); // exhaust
connect("google.com", "80", false); // do not exhaust
}
产生以下输出:
Exhausting iterator
asio.misc -- Element not found
Exhausting copy of iterator
system -- Success