开发者

Async Resolve with Boost.Asio

I'm t开发者_C百科rying to asynchronously resolve a ftp host using Boost.Asio.

Here's what I've tried so far:

#include <iostream>
#include <string>

#include <boost/asio.hpp>
#include <boost/bind.hpp>

using boost::asio::ip::tcp;

class FtpSession {
public:
    void Connect(std::string& host) {
        boost::asio::io_service io_service;

        tcp::resolver resolver(io_service);
        tcp::resolver::query query(host, "ftp");

        resolver.async_resolve(query,
            boost::bind(&FtpSession::OnResolve, this, 
                boost::asio::placeholders::error, 
                    boost::asio::placeholders::iterator));
    }

private:
    void OnResolve(const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator) {
        if (!err)
        {
            std::cout << "resolved!";
        }
        else
        {
            std::cout << "error.";
        }
    }
};

int main() {
    FtpSession session;
    std::string host("ftp.remotesensing.org");

    session.Connect(host);

    return 0;
}

But for some reason, when I execute it, it just doesn't print anything:

alon@alon-GA-73PVM-S2H:~/Desktop$ g++ -o test -lboost_system test.cc
alon@alon-GA-73PVM-S2H:~/Desktop$ ./test
alon@alon-GA-73PVM-S2H:~/Desktop$

No errors or warnings at the compilation though.

How can I fix this?


You need to call io_service.run() to actually do the work methinks. Think of the async_resolve as a request in a request queue - you need something (the io_service) to process the requests in the queue, and to do that, you actually need to run() it! In this case, it will see one request, execute it, call the handler and then exit.


Your io_service and ip::tcp::resolver object are going out of scope. Move both of them into members of the FtpSession class, then invoke io_service::run inside of main after session.Connect(host) to start the event loop.

I answered a similar question a few days ago that may help you as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜