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 }
作者:长风
Email:844064492@qq.com
QQ群:607717453
Git:https://github.com/zhaohu19910409Dz
开源项目:https://github.com/OriginMEK/MEK
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
感谢您的阅读。如果觉得有用的就请各位大神高抬贵手“推荐一下”吧!你的精神支持是博主强大的写作动力。
如果觉得我的博客有意思,欢迎点击首页左上角的“+加关注”按钮关注我!