Advertisement
Guest User

How do I perform a nonblocking read using asio

a guest
Feb 26th, 2012
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. void foo()
  2. {
  3. io_service io_svc;
  4. serial_port ser_port(io_svc, "your string here");
  5. deadline_timer timeout(io_svc);
  6. unsigned char my_buffer[1];
  7. bool data_available = false;
  8.  
  9. ser_port.async_read_some(boost::asio::buffer(my_buffer),
  10. boost::bind(&read_callback, boost::ref(data_available), boost::ref(timeout),
  11. boost::asio::placeholders::error,
  12. boost::asio::placeholders::bytes_transferred));
  13. timeout.expires_from_now(boost::posix_time::milliseconds(<<your_timeout_here>>));
  14. timeout.async_wait(boost::bind(&wait_callback, boost::ref(ser_port),
  15. boost::asio::placeholders::error));
  16.  
  17. io_svc.run(); // will block until async callbacks are finished
  18.  
  19. if (!data_available)
  20. {
  21. kick_start_the_device();
  22. }
  23. }
  24.  
  25. void read_callback(bool& data_available, deadline_timer& timeout, const boost::system::error_code& error, std::size_t bytes_transferred)
  26. {
  27. if (error || !bytes_transferred)
  28. {
  29. // No data was read!
  30. data_available = false;
  31. return;
  32. }
  33.  
  34. timeout.cancel(); // will cause wait_callback to fire with an error
  35. data_available = true;
  36. }
  37.  
  38. void wait_callback(serial_port& ser_port, const boost::system::error_code& error)
  39. {
  40. if (error)
  41. {
  42. // Data was read and this timeout was canceled
  43. return;
  44. }
  45.  
  46. ser_port.cancel(); // will cause read_callback to fire with an error
  47. }
  48.  
  49. boost::asio::ip::tcp::socket socket(io_service);
  50. ...
  51. boost::asio::socket_base::non_blocking_io command(true);
  52. socket.io_control(command);
  53.  
  54. boost::asio::ip::tcp::socket socket(io_service);
  55. ...
  56. boost::asio::socket_base::bytes_readable command(true);
  57. socket.io_control(command);
  58. std::size_t bytes_readable = command.get();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement