加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – asio ::读取超时

发布时间:2020-12-16 05:58:17 所属栏目:百科 来源:网络整理
导读:我需要知道如何读取(同步或异步不重要)超时.我想检查设备是否与串行端口连接. 为此,我使用asio :: write,然后我等待设备的响应. 如果设备连接asio :: read(serial,boost :: asio :: buffer( r,1))工作正常,但如果没有设备停止程序,那就是为什么我需要超时 我
我需要知道如何读取(同步或异步不重要)超时.我想检查设备是否与串行端口连接.

为此,我使用asio :: write,然后我等待设备的响应.

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

我知道我需要一个deadline_timer,但我不知道如何在async_read函数中使用它.

它的工作原理的一个例子将是非常有帮助的.

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

解决方法

code posted by Igor R.没有为我编译.这是我的改进版本的他的代码,这是完美的工作.它使用lambdas来摆脱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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读