kevin55

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1 #include <iostream>
 2 #include <boost/asio.hpp>
 3 
 4 using namespace std;
 5 using namespace boost::asio;
 6 
 7 int main()
 8 {
 9     try
10     {
11         cout << "server start." << endl;
12         io_service ios;
13 
14         ip::tcp::acceptor acc(ios,
15             ip::tcp::endpoint(ip::tcp::v4(),6688));
16 
17         cout << acc.local_endpoint().address() << endl;
18 
19         while (true)
20         {
21             ip::tcp::socket sock(ios);
22             acc.accept(sock);
23 
24             cout << "client:" ;
25             cout << sock.remote_endpoint().address() << endl;
26 
27             sock.write_some(buffer("hello asio"));
28         }
29     }
30     catch (std::exception& e)
31     {
32         cout << e.what() << endl;
33     }
34 
35     return 0;
36 }

tcp client:

 1 #include <boost/asio.hpp>
 2 #include <iostream>
 3 
 4 using namespace std;
 5 using namespace boost::asio;
 6 
 7 void client(io_service &ios)
 8 {
 9     try
10     {
11         cout << "client start." << endl;
12 
13         ip::tcp::socket sock(ios);
14         ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"),6688);
15 
16         sock.connect(ep);
17 
18         vector<char> str(100,0);
19         sock.read_some(buffer(str));
20         cout << "receive from " << sock.remote_endpoint().address();
21         cout << &str[0] << endl;
22     }
23     catch (std::exception& e)
24     {
25         cout << e.what() << endl;
26     }
27 }
28 
29 void print(const boost::system::error_code&)
30 {
31     cout << "test wait..." << endl;
32 }
33 
34 int main()
35 {
36     io_service ios;
37     deadline_timer at(ios, boost::posix_time::seconds(5));
38     at.async_wait(print);
39 
40     cout << "it show before at exired" <<endl;
41     ios.run();
42     return 0;
43 }

 

posted on 2014-06-09 23:36  kernel_main  阅读(2300)  评论(0编辑  收藏  举报