I am programming a tcp async client, but it fails to connect when I use "localhost" instead of "127.0.0.1". I mean, 127.0.0.1 works great but localhost fails miserabily. Please, any help fixing it or at least any explanation of what is going on? Maybe I am missusing the tcp::resolver and its results/iterators?
PD: Funny thing is that when using sync version to connect it works with both adresses (I mean using 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;
}
Thank you very much.
Aucun commentaire:
Enregistrer un commentaire