SO_RCVTIME和SO_RCVTIMEO不影响Boost.Asio操作

8
以下是我的代码
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。仍然无法在指定的时间内超时。

2个回答

19

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

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

使用std::future

Boost.Asio提供了C++11 futures支持。当boost::asio::use_future作为异步操作的完成处理程序时,启动函数将返回一个std::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行为
首先,在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操作来避免EAGAINEWOULDBLOCK

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不支持这一点:链接1

socket::native_non_blocking(bool mode)

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


我不能说我完全理解这个实现,但感觉它可以工作。它在套接字上调用recv,可能会返回超时。然后,不要调用poll,只需返回超时错误即可。 - Tom Quarendon
至少在Windows上,设置SO_RCVTIMEO确实有效(仅仅是这样,没有设置非阻塞模式等),至少在boost 1.64上,它只是做你所期望的事情。目前不确定为什么在非Windows平台上不能正常工作。 - Tom Quarendon

0

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

尽管混合使用boost和系统调用可能无法产生预期的结果。

供参考:

SO_RCVTIMEO

设置超时值,指定输入函数等待完成的最长时间。它接受一个timeval结构,其中包含秒数和微秒数,指定等待输入操作完成的时间限制。如果接收操作已经阻塞了这么长时间而没有接收到其他数据,则会返回部分计数或将errno设置为[EAGAIN][EWOULDBLOCK](如果未接收到数据)。此选项的默认值为零,表示接收操作不会超时。此选项采用timeval结构。请注意,并非所有实现都允许设置此选项。

但是,此选项仅对读取操作有效,而不对其他可能在套接字上等待的低级函数(例如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;
}

谢谢你的提醒。但即使我不能利用SO_RCVTIMEO异步接收指定的超时时间。 - ench4nt3r
@fneig请尝试修改后的答案并让我知道 :) - baol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接