如何在 boost::asio udp::socket 接收时设置超时?
我创建了一个单线程应用程序,它通过 UDP 与另一个线程进行交换。当第二个断开连接时,我的 socket::receive_from 阻塞,我不知道如何解决这个问题,而不将整个程序更改为多线程或异步交互。
我认为接下来可能是一个解决方案:
std::chrono::milliseconds timeout{4};
boost::system::error_code err;
data_t buffer(kPackageMaxSize);
std::size_t size = 0;
const auto status = std::async(std::launch::async,
[&]{
size = socket_.receive_from(boost::asio::buffer(buffer), dst_, 0, err);
}
).wait_for(timeout);
switch (status)
{
case std::future_status::timeout: /*...*/ break;
}
但是我遇到了一个新问题:Qt Creator(GDB 11.1)(我还没有能力尝试一些东西)在调试时开始崩溃。如果没有它运行,该解决方案也并不总是有效。
I create an one-thread application which exchanges with another one via UDP. When the second is disconnecting, my socket::receive_from blocks and I don't know how to solve this problem not changing the entire program into multi-threads or async interactions.
I thought that next may be a solution:
std::chrono::milliseconds timeout{4};
boost::system::error_code err;
data_t buffer(kPackageMaxSize);
std::size_t size = 0;
const auto status = std::async(std::launch::async,
[&]{
size = socket_.receive_from(boost::asio::buffer(buffer), dst_, 0, err);
}
).wait_for(timeout);
switch (status)
{
case std::future_status::timeout: /*...*/ break;
}
But I achieved a new problem: Qt Creator (GDB 11.1) (I don't have ability to try something yet) began to fall when I am debugging. If it runs without, the solution also not always works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Asio 代表“异步 IO”。正如您可能怀疑的那样,这意味着异步 IO 是一个内置功能,它是该库的全部目的。请参阅overview/core/async.html: 没有线程的并发
没有必要使
std::async
变得复杂。对于您的情况,我建议将async_receive_from
与use_future
一起使用,因为它最接近您选择的模型:Live On Coliru
Coliru 输出:
本地演示超时和成功路径:
Asio stands for "Asynchronous IO". As you might suspect, this means that asynchronous IO is a built-in feature, it's the entire purpose of the library. See overview/core/async.html: Concurrency Without Threads
It's not necessary to complicate with
std::async
. In your case I'd suggest usingasync_receive_from
withuse_future
, as it is closest to the model you opted for:Live On Coliru
The Coliru output:
Locally demonstrating both timeout and successful path: