2

Is there a way to check for data for a certain time in asio?

I have a client with an asio socket which has a Method

bool ASIOClient::hasData()
{
    return m_socket->available();
}

And i'd like to have some kind of delay here so it checks for data for like 1 second max and returns more ealy. Moreover i don't want to poll it for obvious reason that it meight take a second. The reaseon why i use this is, that i do send data to a client and wait for the respond. If he doesnt respond in a certain time i'd close the socket. Thats what the hasData is mentioned for.

I know that it is nativ possible with an select and an fd_set.


The asio Client is created in an Accept method of the server socket class and later used to handle requests and send back data to the one who connected here.

int ASIOServer::accept(const bool& blocking)
{
    auto l_sock = std::make_shared<asio::ip::tcp::socket>(m_io_service);
    m_acceptor.accept(*l_sock);
    auto l_client = std::make_shared<ASIOClient>(l_sock);
    return 0;
}
Tanner Sansbury
  • 51,153
  • 9
  • 112
  • 169
bemeyer
  • 6,154
  • 4
  • 36
  • 86

1 Answers1

1

You just need to attempt to read.

The usual approach is to define deadlines for all asynchronous operations that could take "long" (or even indefinitely long).

This is quite natural in asynchronous executions:

Just add a deadline timer:

 boost::asio::deadline_timer tim(svc);
 tim.expires_from_now(boost::posix_time::seconds(2));
 tim.async_wait([](error_code ec) {
      if (!ec) // timer was not canceled, so it expired
      {
           socket_.cancel(); // cancel pending async operation
      }
 });

If you want to use it with synchronous calls, you can with judicious use of poll() instead of run(). See this answer: boost::asio + std::future - Access violation after closing socket which implements a helper await_operation that runs a single operations synchronously but under a timeout.

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • thanks for the answer. I think it is a bit missleading that its cald ASIOClient. Here it is a Clienthandle of a server, so basically a wrapper for writing and reading it does not have its own service. – bemeyer Nov 21 '15 at 15:35
  • And my bad, i missed that i do not use boost i use ASIO as Standalone so there is no deadline_timer if i see that right. – bemeyer Nov 21 '15 at 15:40
  • There should be a deadline_timer. Perhaps you also have a `high_resolution_timer` you can use (which uses c++11 `std::chrono::high_resolution_clock`) – sehe Nov 21 '15 at 15:49
  • @BennX I have no clue where "ASIOClient" and "Clienthandle" come from. Asio sockets cannot be constructed without a service reference. – sehe Nov 21 '15 at 15:53
  • Lets continue here if you have time: http://chat.stackoverflow.com/rooms/95802/check-for-data-with-timing – bemeyer Nov 21 '15 at 15:55