基于Boost的同步TCP通信

时间:2022-09-09 11:33:47

1:客户端

  

 1 #include <iostream>
 2 #include <boost/asio.hpp>
 3 
 4 using namespace boost;
 5 using namespace std;
 6 using boost::asio::ip::tcp;
 7 
 8 int main()
 9 {
10         try
11         {
12                 typedef tcp::endpoint endpoint_type;
13                 typedef tcp::socket     socket_type;
14                 typedef asio::ip::address       address_type;
15 
16                 cout<<"client start."<<endl;
17                 asio::io_service io;
18 
19                 socket_type sock(io);
20                 endpoint_type ep(address_type::from_string("127.0.0.1"),6688);
21 
22                 sock.connect(ep);
23                 cout<<sock.available()<<endl;
24 
25                 vector<char> str(sock.available()+1,0);
26                 sock.receive(asio::buffer(str));
27 
28                 cout<<"receive from"<<sock.remote_endpoint().address();
29                 cout<<&str[0]<<endl;
30 
31         }
32         catch(std::exception& e)
33         {
34                 cout<<e.what()<<endl;
35         }
36         return 0;
37 }

2:服务端

  

 1 #include <iostream>
 2 #include <boost/asio.hpp>
 3 
 4 using namespace boost;
 5 using namespace std;
 6 using boost::asio::ip::tcp;
 7 
 8 int main()
 9 {
10         try
11         {
12                 typedef tcp::acceptor acceptor_type;
13                 typedef tcp::endpoint endpoint_type;
14                 typedef tcp::socket     socket_type;
15 
16                 cout<<"server start."<<endl;
17                 asio::io_service io;
18 
19                 acceptor_type acceptor(io,endpoint_type(tcp::v4(),6688));
20                 cout<<acceptor.local_endpoint().address()<<endl;
21 
22                 for(;;)
23                 {
24                         socket_type sock(io);
25                         acceptor.accept(sock);
26 
27                         cout<<"client:";
28                         cout<<sock.remote_endpoint().address()<<endl;
29 
30                         sock.send(asio::buffer("hello asio"));
31                 }
32         }
33         catch(std::exception& e)
34         {
35                 cout<<e.what()<<endl;
36         }
37         return 0;
38 }