【问题标题】:Bind resolve_handler to resolver async_resolve using boost::asio使用 boost::asio 将 resolve_handler 绑定到解析器 async_resolve
【发布时间】:2011-08-24 23:38:27
【问题描述】:

我有这个代码。如何将我的方法 resolve_handler 与预期的迭代器和错误参数绑定?分解连接逻辑的方法正确吗?

void FileClient::start() 
{ 
    try {
        boost::asio::ip::tcp::resolver::query query("ip", "port");
        resolver_.async_resolve(query, boost::bind(
            &FileClient::resolve_handler, this
        ));
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }
}

void FileClient::resolve_handler(const boost::system::error_code &_error,
                                 boost::asio::ip::tcp::resolver::iterator _it)
{ 
    if (!_error) 
        socket_.async_connect(*_it, boost::bind(
            &FileClient::connect_handler, this, boost::asio::placeholders::error
        ));
    else 
        std::cerr << "resolve_handler error: " << _error << std::endl; 
}

【问题讨论】:

    标签: c++ boost boost-asio


    【解决方案1】:

    boost.asio教程中有例子,比如来自这个HTTP async client

    tcp::resolver::query query(server, "http");
        resolver_.async_resolve(query,
            boost::bind(&client::handle_resolve, this,
              boost::asio::placeholders::error,
              boost::asio::placeholders::iterator));
    

    ...

    void handle_resolve(const boost::system::error_code& err,
                        tcp::resolver::iterator endpoint_iterator)
    {
        if (!err)
        {
            // Attempt a connection to the first endpoint in the list. Each endpoint
            // will be tried until we successfully establish a connection.
             tcp::endpoint endpoint = *endpoint_iterator;
             socket_.async_connect(endpoint,
                             boost::bind(&client::handle_connect, this,
                             boost::asio::placeholders::error, ++endpoint_iterator));
        }
        else
        {
            std::cout << "Error: " << err.message() << "\n";
        }
    }
    

    (他们的handle_connect 继续根据需要增加endpoint_iterator

    【讨论】:

    • 它有效,不知道为什么我卡在这里,谢谢(我似乎无法接受或关闭 qn)。
    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多