c++ - 在 ASIO 中对 UDP 调用 receive_from 应用超时

标签 c++ c++11 networking asio

我有以下 ASIO 代码,它同步读取 UDP 数据包。问题是如果在给定的时间范围(30 秒)内没有给定大小的数据包到达,我希望 recieve_from 函数在特定超时时返回某种错误。

for (;;)
{
  boost::array<char, 1000> recv_buf;
  udp::endpoint remote_endpoint;
  asio::error_code error;

  socket.receive_from(asio::buffer(recv_buf),   // <-- require timeout
      remote_endpoint, 0, error);

  if (error && error != asio::error::message_size)
    throw asio::system_error(error);

  std::string message = make_daytime_string();

  asio::error_code ignored_error;
  socket.send_to(asio::buffer(message),
      remote_endpoint, 0, ignored_error);
}

查看文档,非面向 UDP 的调用支持超时机制。

在 ASIO 中使用同步 UDP 调用超时的正确方法是什么(如果可能的话也是可移植的)?

最佳答案

据我所知,这是不可能的。通过运行同步 receive_from您已通过系统调用阻止代码执行 recvmsg来自 #include <sys/socket.h> .

随着可移植性的发展,我不能代表 Windows,但 linux/bsd C 风格的解决方案看起来像这样:

void SignalHandler(int signal) {
  // do what you need to do, possibly informing about timeout and calling exit()
}

...
struct sigaction signal_action;
signal_action.sa_flags = 0;
sigemptyset(&signal_action.sa_mask);
signal_action.sa_handler = SignalHandler;
if (sigaction(SIGALRM, &signal_action, NULL) == -1) {
  // handle error
}
...
int timeout_in_seconds = 5;
alarm(timeout_in_seconds);
...
socket.receive_from(asio::buffer(recv_buf), remote_endpoint, 0, error);
...
alarm(0);

如果这根本不可行,我会建议完全异步并在 boost::asio::io_service 中运行它.

关于c++ - 在 ASIO 中对 UDP 调用 receive_from 应用超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43645534/

相关文章:

c++ - 如何获取内存管理中下一个 block 的地址?

c++ - 构造函数被调用了多少次?

networking - 如何在 TEE 之后处理镜像(重复)iptables 流量?

c++ - 使用 C++ 在 Windows 上发送/接收以太网帧

c++ - GetFullPathNameA 不返回 DLL 的路径

c++ - 什么是 "rvalue reference for *this"?

c++ - CMake : How to change default package name using CPack - linux

c++ - 尝试在多集中插入元素时发生C++ 11编译错误

c++11 - 如何在 shared_ptr 之间实现类似 "dynamic_cast"的运算符?

networking - 重定向域名到本地网络内部ip(不需要外部访问)