title: Reading a Serial Port Asynchronously Boost
body: <p>I am trying to read several bytes asynchronously from a serial port. Currently the code I am using (source is <a href="https://stackoverflow.com/questions/456042/how-do-i-perform-a-nonblocking-read-using-asio">How do I perform a nonblocking read using asio?</a>), only allows me to read 1 byte and then it exits. How do I get it so that the code keeps reading until there is no more incoming data in the serial port? Thanks :)</p>
  
  <pre><code>    void foo()
  {
      boost::asio::io_service io_svc;
      boost::asio::serial_port ser_port(io_svc, "/dev/ttyS0");
      boost::asio::deadline_timer timeout(io_svc);
      unsigned char my_buffer[2];
      bool data_available = false;
  
      ser_port.async_read_some(boost::asio::buffer(my_buffer),
              boost::bind(&amp;read_callback, boost::ref(data_available),
                      boost::ref(timeout),boost::asio::placeholders::error(),
                      boost::asio::placeholders::bytes_transferred()));
      timeout.expires_from_now(boost::posix_time::seconds(30));
      timeout.async_wait(boost::bind(&amp;wait_callback, boost::ref(ser_port),boost::asio::placeholders::error()));
  
      io_svc.run();
  
      io_svc.
  
      if(!data_available)
      {
          ser_port.close();
          cout &lt;&lt; "ser_port was closed";
      }
  
  }
  
  void read_callback(bool&amp; data_available, boost::asio::deadline_timer&amp; timeout, const boost::system::error_code&amp; error, std::size_t bytes_transferred)
  {
      if (error || !bytes_transferred)
      {
          // No data was read!
          data_available = false;
          return;
      }
  
      timeout.cancel();
      data_available = true;
  }
  
  void wait_callback(boost::asio::serial_port&amp; ser_port, const boost::system::error_code&amp; error)
  {
      if (error)
      {
          // Data was read and this timeout was cancelled
  
          return;
      }
  
      ser_port.cancel();
  }
  </code></pre>