Boost logo

Boost Users :

Subject: [Boost-users] boost::asio - Can't get timeout on accept to work
From: Jean-Sebastien Stoezel (js.stoezel_at_[hidden])
Date: 2010-02-18 09:26:06


Hello,

I would like to implement a timeout while accepting a connection on a
TCP socket. I have reviewed the following example:
http://www.boost.org/doc/libs/1_42_0/doc/html/boost_asio/example/timeouts/accept_timeout.cpp

And here is my implementation of it, though it does not seem to wait
for the given timeout... And I don't seem to see
CProtobufSocket::HandleAccept being called.

Could anybody tell me what I am missing with this code?

Thanks!
Jean-Sebastien

int CProtobufSocket::Receive(
   string port,
   google::protobuf::Message & message,
   const boost::posix_time::milliseconds timeout
)
{
   int result = -1;
   boost::asio::io_service ioService;
   boost::asio::ip::tcp::acceptor acceptor(ioService,
boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),
atoi(port.data())));
   boost::asio::ip::tcp::socket socket(ioService);

   try
   {
      boost::asio::deadline_timer mytimer(ioService);

      acceptor.async_accept(socket,
boost::bind(CProtobufSocket::HandleAccept,
boost::asio::placeholders::error, result));
      mytimer.expires_from_now(timeout);
      mytimer.async_wait(boost::bind(CProtobufSocket::Close, &acceptor));

      if(0 == result)
      {
         // receive on the socket.
          result = Receive(socket, message, timeout);
      }
      else
      {}

   }
   catch (std::exception& e)
   {
      // jstoezel 2910208: removes warning C4101: 'e' : unreferenced
local variable
      e;
   }

   try
   {
      socket.shutdown(socket.shutdown_both);
      socket.close();
   }
   catch (std::exception& e)
   {
      // jstoezel 2910208: removes warning C4101: 'e' : unreferenced
local variable
      e;
   }

   return result;
}

void CProtobufSocket::Close(
   boost::asio::ip::tcp::acceptor * acceptor
   )
{
   acceptor->close();
}

void CProtobufSocket::HandleAccept(const boost::system::error_code
&err, int & result)
{
   err;
   if(err)
   {}
   else
   {
      result = 0;
   }
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net