且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用asio的定时器实现带超时的connect,备忘

更新时间:2022-09-17 14:05:38

  1. // test.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include <boost/asio.hpp>  
  6. #include <boost/bind.hpp>  
  7. #include <boost/date_time/posix_time/posix_time_types.hpp>  
  8. #include <iostream>  
  9.   
  10. using namespace boost::asio;  
  11. using boost::asio::ip::tcp;  
  12.   
  13. class connect_handler  
  14. {  
  15. public:  
  16.     connect_handler(io_service& ios)  
  17.         : io_service_(ios),  
  18.         timer_(ios),  
  19.         socket_(ios)  
  20.     {  
  21.         socket_.async_connect(  
  22.             tcp::endpoint(boost::asio::ip::address_v4::loopback(), 3212),  
  23.             boost::bind(&connect_handler::handle_connect, this,  
  24.             boost::asio::placeholders::error));  
  25.   
  26.         timer_.expires_from_now(boost::posix_time::seconds(5));  
  27.         timer_.async_wait(boost::bind(&connect_handler::close, this));  
  28.     }  
  29.   
  30.     void handle_connect(const boost::system::error_code& err)  
  31.     {  
  32.         if (err)  
  33.         {  
  34.             std::cout << "Connect error: " << err.message() << "\n";  
  35.         }  
  36.         else  
  37.         {  
  38.             std::cout << "Successful connection\n";  
  39.         }  
  40.     }  
  41.   
  42.     void close()  
  43.     {  
  44.         socket_.close();  
  45.     }  
  46.   
  47. private:  
  48.     io_service& io_service_;  
  49.     deadline_timer timer_;  
  50.     tcp::socket socket_;  
  51. };  
  52.   
  53. int main()  
  54. {  
  55.     try  
  56.     {  
  57.         io_service ios;  
  58.         tcp::acceptor a(ios, tcp::endpoint(tcp::v4(), 32123), 1);  
  59.   
  60.         // Make lots of connections so that at least some of them will block.  
  61.         connect_handler ch1(ios);  
  62.         //connect_handler ch2(ios);  
  63.         //connect_handler ch3(ios);  
  64.         //connect_handler ch4(ios);  
  65.         //connect_handler ch5(ios);  
  66.         //connect_handler ch6(ios);  
  67.         //connect_handler ch7(ios);  
  68.         //connect_handler ch8(ios);  
  69.         //connect_handler ch9(ios);  
  70.   
  71.         ios.run();  
  72.     }  
  73.     catch (std::exception& e)  
  74.     {  
  75.         std::cerr << "Exception: " << e.what() << "\n";  
  76.     }  
  77.   
  78.     return 0;  
  79. }