C++11 Boost::asio async_connect在使用时无法解决问题;“本地主机”;而不是",;127.0.0.1“;
我正在编写一个tcp异步客户机,但当我使用“localhost”而不是“127.0.0.1”时,它无法连接。我的意思是,127.0.0.1工作得很好,但是localhost失败得很惨。请帮忙修理一下,或者至少解释一下发生了什么?也许我误用了tcp::resolver及其结果/迭代器 PD:有趣的是,当使用同步版本连接时,它可以与两个地址一起工作(我的意思是使用boost::asio::connect(套接字、端点、错误);)C++11 Boost::asio async_connect在使用时无法解决问题;“本地主机”;而不是",;127.0.0.1“;,c++11,boost-asio,C++11,Boost Asio,我正在编写一个tcp异步客户机,但当我使用“localhost”而不是“127.0.0.1”时,它无法连接。我的意思是,127.0.0.1工作得很好,但是localhost失败得很惨。请帮忙修理一下,或者至少解释一下发生了什么?也许我误用了tcp::resolver及其结果/迭代器 PD:有趣的是,当使用同步版本连接时,它可以与两个地址一起工作(我的意思是使用boost::asio::connect(套接字、端点、错误);) #包括 #包括 #包括 使用boost::asio::ip::tcp;
#包括
#包括
#包括
使用boost::asio::ip::tcp;
类客户端
{
公众:
客户()
:io_context(),
接受者(io_上下文),
套接字(io_上下文)
{
}
无效启动(常量字符*主机,常量字符*端口)
{
tcp::解析器解析器(io_上下文);
tcp::resolver::results\u type endpoints=resolver.resolve(主机、端口)//
socket.async_connect(端点->端点(),[=](boost::system::error_code error)
{
如果(!错误)
标准::cout
#include <iomanip>
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
class client
{
public:
client()
: io_context(),
acceptor(io_context),
socket(io_context)
{
}
void start(const char* host, const char* port)
{
tcp::resolver resolver(io_context);
tcp::resolver::results_type endpoints = resolver.resolve(host, port);//
socket.async_connect(endpoints->endpoint(), [=](boost::system::error_code error)
{
if (!error)
std::cout << "Connecting to " << host << ":" << port << "\n";
else
start(host, port);
});
}
void poll()
{
io_context.poll();
}
private:
boost::asio::io_context io_context;
tcp::acceptor acceptor;
tcp::socket socket;
};
int main(int argc, char* argv[])
{
if (argc != 1 && argc != 3)
{
std::cout << "async.exe <host> <port>" << std::endl;
return 0;
}
const char* host = (argc == 1 ? "localhost" : argv[1]);
const char* port = (argc == 1 ? "5031" : argv[2]);
try
{
std::cout << "Trying to connect to " << host << ":" << port << "...\n";
client c;
c.start(host, port);
while (true)
{
c.poll();
Sleep(100);
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}