【发布时间】:2020-10-02 09:30:05
【问题描述】:
我正在编写一个 tcp 异步客户端,但是当我使用“localhost”而不是“127.0.0.1”时它无法连接。我的意思是,127.0.0.1 效果很好,但 localhost 却惨遭失败。请帮助修复它或至少解释发生了什么?也许我错过了 tcp::resolver 及其结果/迭代器?
PD:有趣的是,当使用同步版本连接时,它适用于两个地址(我的意思是使用 boost::asio::connect(socket, endpoints, error);)
#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;
}
非常感谢。
【问题讨论】:
标签: c++11 boost-asio