boost asio

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值