SO_RCVTIME和SO_RCVTIMEO不会影响Boost.Asio的操作

SO_RCVTIME and SO_RCVTIMEO not affecting Boost.Asio operations

本文关键字:SO Asio Boost 操作 影响 RCVTIME RCVTIMEO      更新时间:2023-10-16

下面是我的代码

boost::asio::io_service io;
boost::asio::ip::tcp::acceptor::reuse_address option(true);
boost::asio::ip::tcp::acceptor accept(io);
boost::asio::ip::tcp::resolver resolver(io);
boost::asio::ip::tcp::resolver::query query("0.0.0.0", "8080");
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
accept.open(endpoint.protocol());
accept.set_option(option);
accept.bind(endpoint);
accept.listen(30);
boost::asio::ip::tcp::socket ps(io);
accept.accept(ps);
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
//setsockopt(ps.native(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
setsockopt(ps.native(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
char buf[1024];
ps.async_receive(boost::asio::buffer(buf, 1024), boost::bind(fun));
io.run();

当我使用 Telnet 进行连接但不发送数据时,它不会因 Telnet 超时而断开连接。需要做才能让 setsockopt 发挥作用吗?谢谢!

我已将SO_RCVTIMEO修改为SO_SNDTIMEO。仍然无法在指定时间内超时

SO_RCVTIMEOSO_SNDTIMEO套接字选项与 Boost.Asio 一起使用很少会产生所需的行为。 请考虑使用以下两种模式之一:

async_wait()的组合操作

可以使用 Boost.Asio 计时器编写具有超时的异步读取操作,并使用async_receive()操作编写具有async_wait()操作的操作。 此方法在 Boost.Asio 超时示例中进行了演示,类似于:

// Start a timeout for the read.
boost::asio::deadline_timer timer(io_service);
timer.expires_from_now(boost::posix_time::seconds(1));
timer.async_wait(
  [&socket, &timer](const boost::system::error_code& error)
  {
    // On error, such as cancellation, return early.
    if (error) return;
    // Timer has expired, but the read operation's completion handler
    // may have already ran, setting expiration to be in the future.
    if (timer.expires_at() > boost::asio::deadline_timer::traits_type::now())
    {
      return;
    } 
    // The read operation's completion handler has not ran.
    boost::system::error_code ignored_ec;
    socket.close(ignored_ec);
  });
// Start the read operation.
socket.async_receive(buffer,
  [&socket, &timer](const boost::system::error_code& error,
    std::size_t bytes_transferred)
  {
    // Update timeout state to indicate the handler has ran.  This
    // will cancel any pending timeouts.
    timer.expires_at(boost::posix_time::pos_infin);
    // On error, such as cancellation, return early.
    if (error) return;
    // At this point, the read was successful and buffer is populated.
    // However, if the timeout occurred and its completion handler ran first,
    // then the socket is closed (!socket.is_open()).
  });
请注意,两个

异步操作可能在同一迭代中完成,从而使两个完成处理程序都准备好成功运行。 因此,两个完成处理程序都需要更新和检查状态的原因。 有关如何管理状态的更多详细信息,请参阅此答案。

使用std::future

Boost.Asio为C++11期货提供支持。 当boost::asio::use_future作为异步操作的完成处理程序提供时,启动函数将返回一个std::future,该将在操作完成后完成。 由于std::future支持定时等待,因此可以利用它来使操作超时。 请注意,由于调用线程将被阻塞等待将来,因此至少必须有一个其他线程正在处理io_service,以允许async_receive()操作进行并实现承诺:

// Use an asynchronous operation so that it can be cancelled on timeout.
std::future<std::size_t> read_result = socket.async_receive(
   buffer, boost::asio::use_future);
// If timeout occurs, then cancel the read operation.
if (read_result.wait_for(std::chrono::seconds(1)) == 
    std::future_status::timeout)
{
  socket.cancel();
}
// Otherwise, the operation completed (with success or error).
else
{
  // If the operation failed, then read_result.get() will throw a
  // boost::system::system_error.
  auto bytes_transferred = read_result.get();
  // process buffer
}

为什么SO_RCVTIMEO不起作用

系统行为

SO_RCVTIMEO文档指出,该选项仅影响执行套接字 I/O 的系统调用,例如 read()recvmsg() 。 它不会影响事件解复用器,例如 select()poll() ,它们只监视文件描述符以确定何时可以发生 I/O 而不会阻塞。 此外,当确实发生超时时,I/O 调用将返回 -1 失败,并将errno设置为 EAGAINEWOULDBLOCK

指定报告错误之前的接收或发送超时。[...]如果未传输任何数据并且已达到超时,则返回-1 errno 设置为 EAGAINEWOULDBLOCK [...]超时仅对执行套接字 I/O 的系统调用(例如,read()recvmsg()、[...](有效;超时对select()poll()epoll_wait()等没有影响。

当基础文件描述符设置为非阻塞时,如果资源不是立即可用,则执行套接字 I/O 的系统调用将立即返回并带有EAGAINEWOULDBLOCK。 对于非阻塞套接字,SO_RCVTIMEO不会产生任何影响,因为调用将立即返回成功或失败。 因此,要使SO_RCVTIMEO影响系统 I/O 调用,套接字必须阻塞。

提升行为

首先,Boost.Asio 中的异步 I/O 操作将使用事件解复用器,例如 select()poll() 。 因此,SO_RCVTIMEO不会影响异步操作。

接下来,Boost.Asio 的套接字具有两种非阻塞模式的概念(这两种模式都默认为 false(:

  • native_non_blocking()大致对应于文件描述符的非阻塞状态的模式。 此模式会影响系统 I/O 调用。 例如,如果调用 socket.native_non_blocking(true) ,则recv(socket.native_handle(), ...)可能会失败,errno设置为 EAGAINEWOULDBLOCK 。 每当在套接字上启动异步操作时,Boost.Asio 都会启用此模式。
  • non_blocking()影响 Boost.Asio 同步套接字操作的模式。 当设置为 true 时,Boost.Asio 会将底层文件描述符设置为非阻塞,同步 Boost.Asio 套接字操作可能会失败并出现boost::asio::error::would_block(或等效的系统错误(。 设置为 false 时,即使基础文件描述符是非阻塞的,Boost.Asio 也会通过轮询文件描述符并在返回EAGAINEWOULDBLOCK时重新尝试系统 I/O 操作来阻止。

non_blocking()的行为会阻止SO_RCVTIMEO产生所需的行为。 假设调用了socket.receive()并且数据既不可用也不接收:

  • 如果non_blocking()为 false,则系统 I/O 调用将按SO_RCVTIMEO超时。 但是,Boost.Asio 随后会立即阻止对文件描述符的轮询,使其可读,这不受SO_RCVTIMEO的影响。 最终结果是调用方在socket.receive()中被阻止,直到收到数据或失败,例如远程对等体关闭连接。
  • 如果non_blocking()为 true,则基础文件描述符也是非阻塞的。 因此,系统I/O调用将忽略SO_RCVTIMEO,立即返回EAGAINEWOULDBLOCK,导致socket.receive()失败并boost::asio::error::would_block

理想情况下,要使SO_RCVTIMEO与 Boost.Asio 一起运行,需要将native_non_blocking()设置为 false,以便SO_RCVTIMEO可以生效,但也要将non_blocking()设置为 true 以防止对描述符进行轮询。 但是,Boost.Asio不支持这一点:

socket::native_non_blocking(bool mode)

如果模式false,但non_blocking()的当前值是true,则此函数失败并显示boost::asio::error::invalid_argument,因为组合没有意义。

由于您正在接收数据,因此可能需要设置: SO_RCVTIMEO 而不是SO_SNDTIMEO

尽管混合提升和系统调用可能不会产生预期的结果。

供参考:

SO_RCVTIMEO

设置超时值,该值指定输入函数在完成之前等待的最长时间。它接受一个时间值 具有秒数和微秒数的结构,指定 限制等待输入操作完成的时间。如果 接收操作已阻止了很长时间而没有接收 其他数据,它应返回部分计数或 errno 设置为 如果未收到数据,则[EAGAIN][EWOULDBLOCK]。此的默认值 选项为零,表示接收操作不应 超时。此选项采用时间值结构。请注意,并非全部 实现允许设置此选项。

然而,此选项仅对读取操作有效,对异步实现中可能等待套接字的其他低级函数(例如 select 和 epoll(没有影响,并且似乎也不会影响异步 asio 操作。

我在这里找到了来自 boost 的示例代码,可能适用于您的情况。

一个过于简化的示例(用 c++11 编译(:

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>
void myclose(boost::asio::ip::tcp::socket& ps) { ps.close(); }
int main()
{
  boost::asio::io_service io;
  boost::asio::ip::tcp::acceptor::reuse_address option(true);
  boost::asio::ip::tcp::acceptor accept(io);
  boost::asio::ip::tcp::resolver resolver(io);
  boost::asio::ip::tcp::resolver::query query("0.0.0.0", "8080");
  boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query);
  accept.open(endpoint.protocol());
  accept.set_option(option);
  accept.bind(endpoint);
  accept.listen(30);
  boost::asio::ip::tcp::socket ps(io);
  accept.accept(ps);
  char buf[1024];
  boost::asio::deadline_timer timer(io, boost::posix_time::seconds(1));
  timer.async_wait(boost::bind(myclose, boost::ref(ps))); 
  ps.async_receive(boost::asio::buffer(buf, 1024),
           [](const boost::system::error_code& error,
              std::size_t bytes_transferred )
           {
             std::cout << bytes_transferred << std::endl;
           });
  io.run();
  return 0;
}