我需要知道如何读取(同步或异步不重要)超时.我想检查设备是否与串行端口连接.
为此,我使用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); }
原文地址:https://www.jb51.cc/c/113130.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。