将超时到udp call recere_从ASIO中应用

Applying a timeout to UDP call receive_from in ASIO

本文关键字:ASIO 应用 recere 超时 udp call      更新时间:2023-10-16

我具有以下ASIO代码,同步读取UDP数据包。问题是,如果没有给定大小的数据包在给定的时间范围内到达(30秒(,我希望rocieve_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中与Syncronous UDP访问的时间是什么正确的方法(如果可能的话(?

据我所知,这是不可能的。通过运行同步receive_from,您可以通过#include <sys/socket.h>封锁SYSCALL recvmsg执行代码。

随着可移植性的发展,我不能为Windows说话,但是Linux/BSD C-Flavourane解决方案看起来像这样:

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中运行。