boost :: asio :: deadline_timer不会调用handler

时间:2014-06-18 21:13:25

标签: c++ boost boost-asio

我有一个tcp客户端轮询服务器以获取截止日期的答案,这样如果无法访问服务器,则不会阻止客户端。我遇到的问题是async_wait似乎永远不会调用它的处理程序,当它无法连接时有效地阻止客户端。每次调用tcpPoll都会有自己的线程(这就是为什么我创建一个新的io_service),但即使没有多线程也似乎不起作用。此外,NetworkEntity对象可以在其生命周期内多次调用tcpPoll

我的问题是:阻止deadline_timer调用其处理程序的是什么? (以及如何解决它)

这是一些相关的代码,只要没有任何失败(连接,写入,读取)就会工作(对不起,如果它有点长):

void NetworkEntity::stop()
{
    stopped_ = true;
    //close socket
    //cancel timeout
}

void NetworkEntity::check_timeout(const boost::system::error_code& error)
{
    if (stopped_)
        return;
    if (timeout_.expires_at() <= boost::asio::deadline_timer::traits_type::now())
    {
        stop();
        timeout_.expires_at(boost::posix_time::pos_infin);
        std::cout << address_ << " timed out\n";
    }
    timeout_.async_wait(boost::bind(&NetworkEntity::check_timeout, this, boost::asio::placeholders::error));
}

std::vector<std::string> NetworkEntity::tcpPoll(const char* message, const char endOfMessage)
{
    boost::asio::io_service io_service;
    stopped_ = false;
    timeout_.expires_from_now(boost::posix_time::seconds(TIMEOUT_));
    timeout_.async_wait(boost::bind(&NetworkEntity::check_timeout, this, boost::asio::placeholders::error));
    tcp::resolver resolver(io_service);
    start_connect(&io_service, resolver.resolve(tcp::resolver::query(address_, port_)), message, endOfMessage);
    io_service.run();
    //retrieve answer from class
    //return answer
}

void NetworkEntity::start_connect(boost::asio::io_service* io_service, tcp::resolver::iterator endpoint_iterator, const std::string message, const char endOfMessage)
{
    socket_.reset(new tcp::socket(*io_service));
    socket_->async_connect(endpoint_iterator->endpoint(),
        boost::bind(&NetworkEntity::handle_connect, this, io_service, boost::asio::placeholders::error, endpoint_iterator, message, endOfMessage));
}

void NetworkEntity::handle_connect(boost::asio::io_service* io_service, const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator, const std::string message, const char endOfMessage)
{
    if(stopped_)
        return;
    if (err)
    {
        std::cout << "Connect error: " << err.message() << "\n";
        stop();
    }
    else
    {
        start_write(message, endOfMessage);
    }
}

void NetworkEntity::start_write(const std::string message, const char endOfMessage)
{
    std::ostream request_stream(&request_);
    request_stream << message;
    boost::asio::async_write(*socket_, request_,
        boost::bind(&NetworkEntity::handle_write, this, boost::asio::placeholders::error, endOfMessage));
}

void NetworkEntity::handle_write(const boost::system::error_code& error, const char endOfMessage)
{
    if (stopped_)
        return;
    if (!error)
    {
        //sleep for 500ms to let time for the reciever to process info (had a bug on this one)
        start_read(endOfMessage);
    }
    else
    {
        std::cout << "write error : " << error.message() << "\n";
        stop();
    }
}

void NetworkEntity::start_read(const char endOfMessage)
{
    boost::asio::async_read_until(*socket_, answer_, endOfMessage,
        boost::bind(&NetworkEntity::handle_read, this, boost::asio::placeholders::error));
}

void NetworkEntity::handle_read(const boost::system::error_code& error)
{
    if (stopped_)
        return;
    if (error)
    {
        std::cout << "read error : " << error.message() << "\n";
        stop();
    }
    else
    {
        stop();
    }
}

1 个答案:

答案 0 :(得分:2)

我认为你必须与io_service的多个实例混淆。

我认为这是因为在您的代码中,您从未显示如何初始化timeout_。并且您用于连接的io_service实例仅在tcpPoll函数中实例化...这使我相信您不小心在单独的io_service上注册了截止时间计时器,而您没有甚至跑?

这是一个实际有效的版本,注意:

  1. 它已经废除了stopped_布尔值,因为它是不必要的并且必然会混淆
  2. 查看有关如何检测各种程序流的check_timeoutstop的新实现
  3. 完整的代码,自包含,只是你在问题中发布的代码行数少了几行
  4. #include <iostream>
    #include <boost/asio.hpp>
    #include <boost/bind.hpp>
    
    using tcp = boost::asio::ip::tcp;
    
    struct NetworkEntity {
    
        boost::asio::io_service io_service;
        boost::asio::deadline_timer timeout_{io_service};
        std::string address_ = "localhost";
        std::string port_    = "6767";
        int TIMEOUT_         = 3;
        boost::shared_ptr<tcp::socket> socket_;
        boost::asio::streambuf request_, answer_;
    
        void stop()
        {
            if (socket_)
            {
                socket_->cancel();
                socket_->close();
            }
            timeout_.cancel();
            io_service.stop();
        }
    
        void check_timeout(const boost::system::error_code& error)
        {
            if (error != boost::asio::error::operation_aborted)
            {
                stop();
                std::cout << address_ << " timed out\n";
            }
            timeout_.async_wait(boost::bind(&NetworkEntity::check_timeout, this, boost::asio::placeholders::error));
        }
    
        std::vector<std::string> tcpPoll(const char* message, const char endOfMessage)
        {
            timeout_.expires_from_now(boost::posix_time::seconds(TIMEOUT_));
            timeout_.async_wait(boost::bind(&NetworkEntity::check_timeout, this, boost::asio::placeholders::error));
    
            tcp::resolver resolver(io_service);
            start_connect(&io_service, resolver.resolve(tcp::resolver::query(address_, port_)), message, endOfMessage);
    
            io_service.run();
            //retrieve answer from class
            //return answer
            std::ostringstream oss;
            oss << &answer_;
            return { oss.str() };
        }
    
        void start_connect(boost::asio::io_service* io_service, tcp::resolver::iterator endpoint_iterator, const std::string message, const char endOfMessage)
        {
            socket_.reset(new tcp::socket(*io_service));
            socket_->async_connect(endpoint_iterator->endpoint(),
                    boost::bind(&NetworkEntity::handle_connect, this, io_service, boost::asio::placeholders::error, endpoint_iterator, message, endOfMessage));
        }
    
        void handle_connect(boost::asio::io_service* io_service,
                const boost::system::error_code& err,
                tcp::resolver::iterator endpoint_iterator,
                const std::string message,
                const char endOfMessage)
        {
            if (err)
            {
                std::cout << "Connect error: " << err.message() << "\n";
                stop();
            }
            else
            {
                start_write(message, endOfMessage);
            }
        }
    
        void start_write(const std::string message, const char endOfMessage)
        {
            std::ostream request_stream(&request_);
            request_stream << message;
            boost::asio::async_write(*socket_, request_,
                    boost::bind(&NetworkEntity::handle_write, this, boost::asio::placeholders::error, endOfMessage));
        }
    
        void handle_write(const boost::system::error_code& error, const char endOfMessage)
        {
            if (!error)
            {
                //sleep for 500ms to let time for the reciever to process info (had a bug on this one)
                start_read(endOfMessage);
            }
            else
            {
                std::cout << "write error : " << error.message() << "\n";
                stop();
            }
        }
    
        void start_read(const char endOfMessage)
        {
            boost::asio::async_read_until(*socket_, answer_, endOfMessage,
                    boost::bind(&NetworkEntity::handle_read, this, boost::asio::placeholders::error));
        }
    
        void handle_read(const boost::system::error_code& error)
        {
            if (error)
            {
                std::cout << "read error : " << error.message() << "\n";
            }
            stop();
        }
    };
    
    int main()
    {
        NetworkEntity ne;
        for (auto& s : ne.tcpPoll("this is my request", '\n'))
        {
            std::cout << "Line: '" << s << "'\n";
        }
    }