SO_RCVTIME 和 SO_RCVTIMEO 不影响 Boost.Asio 操作

SO_RCVTIME and SO_RCVTIMEO not affecting Boost.Asio operations

下面是我的代码

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 断开连接 timeout.Will 需要做什么才能让 setsockopt 启动? 谢谢!

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

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

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

供参考:

SO_RCVTIMEO

Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.

但是这个选项只对读取操作有影响,对异步实现中可能在套接字上等待的其他低级函数没有影响(例如 select 和 epoll),它似乎不影响异步asio 操作也是如此。

我从 boost 中找到了一个示例代码,可能适用于您的案例 here

一个过度简化的例子(将在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;
}

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

async_wait()

组合运算

可以通过使用 Boost.Asio 计时器和 async_wait() 操作与 async_receive() 操作来组合超时的异步读取操作。这种方法在 Boost.Asio timeout examples 中得到了演示,类似于:

// 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()).
  });

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

使用std::future

Boost.Asio 提供 support for C++11 futures. When boost::asio::use_future 作为异步操作的完成处理程序,启动函数将 return 一个 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 调用失败 returning -1 并将 errno 设置为 EAGAINEWOULDBLOCK.

Specify the receiving or sending timeouts until reporting an error. [...] if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK [...] Timeouts only have effect for system calls that perform socket I/O (e.g., read(), recvmsg(), [...]; timeouts have no effect for select(), poll(), epoll_wait(), and so on.

当底层文件描述符设置为非阻塞时,执行套接字I/O的系统调用将立即return,如果资源不是立即EAGAINEWOULDBLOCK可用的。对于非阻塞套接字,SO_RCVTIMEO 不会有任何影响,因为调用将 return 立即显示成功或失败。因此,要使 SO_RCVTIMEO 影响系统 I/O 调用,套接字必须处于阻塞状态。

Boost.Asio 行为

首先,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 将阻塞,即使底层文件描述符是非阻塞的,通过轮询文件描述符并重新尝试系统 I/O 操作 if EAGAINEWOULDBLOCK 是 returned.

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

  • 如果 non_blocking() 为假,系统 I/O 调用将在每个 SO_RCVTIMEO 超时。但是,Boost.Asio 将立即阻止对文件描述符的轮询以使其可读,这不受 SO_RCVTIMEO 的影响。最终结果是调用方在 socket.receive() 中阻塞,直到收到数据或失败,例如远程对等方关闭连接。
  • 如果non_blocking()为真,则底层文件描述符也是非阻塞的。因此,系统 I/O 调用将忽略 SO_RCVTIMEO,立即 return 和 EAGAINEWOULDBLOCK,导致 socket.receive() 失败并显示 boost::asio::error::would_block.

理想情况下,要让 SO_RCVTIMEO 与 Boost.Asio 一起工作,需要将 native_non_blocking() 设置为 false,这样 SO_RCVTIMEO 才能生效,但也有 non_blocking() 设置为 true 以防止对描述符进行轮询。但是,Boost.Asio 不会 support this:

socket::native_non_blocking(bool mode)

If the mode is false, but the current value of non_blocking() is true, this function fails with boost::asio::error::invalid_argument, as the combination does not make sense.