SO_RCVTIME and SO_RCVTIMEO not affecting Boost.Asio operations

前端 未结 2 1669
自闭症患者
自闭症患者 2020-12-03 04:01

Below is my code

boost::asio::io_service io;
boost::asio::ip::tcp::acceptor::reuse_address option(true);
boost::asio::ip::tcp::acceptor accept(io);
boost::as         


        
2条回答
  •  渐次进展
    2020-12-03 04:34

    Since you are receiving data, you may want to set: SO_RCVTIMEO instead of SO_SNDTIMEO

    Although mixing boost and system calls may not produce the expected results.

    For reference:

    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.

    This option however only has effect on read operations, not on other low level function that may wait on the socket in an asynchronous implementation (e.g. select and epoll) and it seems that it does not affect asynchronous asio operations as well.

    I found an example code from boost that may work for your case here.

    An over simplified example (to be compiled in c++11):

    #include 
    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题