ASIO ::阅读超时 [英] asio::read with timeout

查看:205
本文介绍了ASIO ::阅读超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to know how to read (sync or async doesn't matters) with a timeout. I want to check if a device is connected with a serial port or not.

有关,我用 ASIO ::写然后我等待设备的响应。

For that I use asio::write and then I wait for the response of the device.

如果一个设备连接 ASIO ::阅读(串行,提高:: ASIO ::缓​​冲区(安培; R,1))工作正常,但如果没有设备的程序停止,这就是为什么我需要超时

If a device is connected asio::read(serial, boost::asio::buffer(&r,1)) works fine but if there is no device the program stops, which is is why I need the timeout

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

I know that I need a deadline_timer but I have no idea how to use it in the async_read function.

它是如何工作的一个例子是真正有用的。

An example of how it works would be really helpful.

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

I know that there are many similar threads and I read lot of them but I can't find a solution that helps me solving my problem!

推荐答案

借助 code发表伊戈尔R上。没有编译我。下面是我自己的code,它完美的作品的改进版本。它使用lambda表达式摆脱 set_result 辅助功能。

The code posted by Igor R. did not compile for me. Here is my improved version of his code, which works perfectly. It uses lambdas to get rid of the set_result helper function.

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);
}

这篇关于ASIO ::阅读超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆