ASIO ::阅读超时(asio::read with timeout)

2019-07-03 10:35发布

我需要知道如何阅读(同步或异步不事项)与超时。 我想检查设备是否有串口或不连接。

对于我使用asio::write ,然后我等待设备的响应。

如果一个设备连接asio::read(serial, boost::asio::buffer(&r,1))工作正常,但如果没有设备的程序停止,这就是为什么我需要超时

我知道我需要一个deadline_timer ,但我不知道如何在使用它async_read功能。

它是如何工作的一个例子是真的很有帮助。

我知道,有很多类似的线程,我读了很多人,但我不能找到一个解决方案,可以帮助我解决我的问题!

Answer 1:

该贴由Igor R.代码没有编译我。 这是我对他的代码,它完美的作品改进版。 它使用lambda表达式摆脱的set_result辅助函数。

template <typename SyncReadStream, typename MutableBufferSequence>
void readWithTimeout(SyncReadStream& s, const MutableBufferSequence& buffers, const boost::asio::deadline_timer::duration_type& expiry_time)
{
    boost::optional<boost::system::error_code> timer_result;
    boost::asio::deadline_timer timer(s.get_io_service());
    timer.expires_from_now(expiry_time);
    timer.async_wait([&timer_result] (const boost::system::error_code& error) { timer_result.reset(error); });

    boost::optional<boost::system::error_code> read_result;
    boost::asio::async_read(s, buffers, [&read_result] (const boost::system::error_code& error, size_t) { read_result.reset(error); });

    s.get_io_service().reset();
    while (s.get_io_service().run_one())
    { 
        if (read_result)
            timer.cancel();
        else if (timer_result)
            s.cancel();
    }

    if (*read_result)
        throw boost::system::system_error(*read_result);
}


Answer 2:

不要使用deadline_timerasync_read 。 但是你可以启动两个异步进程:

  1. 一个async_read串口过程。 提高:: ASIO :: serial_port有取消该取消对所有异步操作的方法。
  2. 一个deadline timer与所需的超时。 在完成处理程序deadline_timer可以cancel串行端口。 这应该关闭async_read操作,并调用它完成处理并报告错误。

码:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/array.hpp>

class timed_connection
{
    public:
        timed_connection( int timeout ) :
            timer_( io_service_, boost::posix_time::seconds( timeout ) ),
            serial_port_( io_service_ )
        {
        }

        void start()
        {
              timer_.async_wait
                (
                 boost::bind
                 (
                  &timed_connection::stop, this
                 )
                );

            // Connect socket
            // Write to socket

            // async read from serial port
            boost::asio::async_read
                (
                 serial_port_, boost::asio::buffer( buffer_ ),
                 boost::bind
                 (
                  &timed_connection::handle_read, this,
                  boost::asio::placeholders::error
                 )
                );

            io_service_.run();
        }

    private:
        void stop()
        {  
            serial_port_.cancel();
        }

        void handle_read ( const boost::system::error_code& ec)
        {  
            if( ec )
            {  
                // handle error
            }
            else
            {  
                // do something
            }
        }

    private:
        boost::asio::io_service io_service_;
        boost::asio::deadline_timer timer_;
        boost::asio::serial_port serial_port_;
        boost::array< char, 8192 > buffer_;
};

int main()
{
    timed_connection conn( 5 );
    conn.start();

    return 0;
}


Answer 3:

曾几何时,图书馆笔者提出了以下方式与超时同步读取 (这个例子涉及tcp::socket ,但您可以使用串行端口,而不是):

  void set_result(optional<error_code>* a, error_code b) 
  { 
    a->reset(b); 
  } 


  template <typename MutableBufferSequence> 
  void read_with_timeout(tcp::socket& sock, 
      const MutableBufferSequence& buffers) 
  { 
    optional<error_code> timer_result; 
    deadline_timer timer(sock.io_service()); 
    timer.expires_from_now(seconds(1)); 
    timer.async_wait(boost::bind(set_result, &timer_result, _1)); 


    optional<error_code> read_result; 
    async_read(sock, buffers, 
        boost::bind(set_result, &read_result, _1)); 

    sock.io_service().reset(); 
    while (sock.io_service().run_one()) 
    { 
      if (read_result) 
        timer.cancel(); 
      else if (timer_result) 
        sock.cancel(); 
    } 


    if (*read_result) 
      throw system_error(*read_result); 
  } 


Answer 4:

有没有人或简单的答案本身,因为即使你做了一个异步读取,回调不会被调用,你现在有一个宽松的线周围的地方。

你是对的假设, deadline_timer是可能的解决方案之一,但它需要一些摆弄和共享的状态。 还有的阻止TCP例子 ,但这是async_connect和有它返回时,它没有任何一件很酷的事情。 read不会那么做,最坏的情况-它会崩溃和烧“无效的资源的原因。 所以, deadline timer的事情是你的选择之一,但实际上是一个更简单的一个,即去有点像这样:

boost::thread *newthread = new boost::thread(boost::bind(&::try_read));
if (!newthread->timed_join(boost::posix_time::seconds(5))) {
    newthread->interrupt();
}

基本上,做读取在另一个线程,如果超时,把它扼杀掉。 您应该阅读起来如Boost.Threads 。

如果中断,确保资源被全部关闭。



文章来源: asio::read with timeout