gpt4 book ai didi

android - boost Android Asio 连接错误

转载 作者:行者123 更新时间:2023-11-30 02:48:49 27 4
gpt4 key购买 nike

我正在使用 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;
}

最佳答案

调试循环正在耗尽迭代器,导致 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

关于android - boost Android Asio 连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21791063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com