boost.asio: demo.

摘要:#include #include #include #include #include #include #include #include #include usingnamespaceboost::asio; intmain() { io

demo1:tcpsocket

#include<iostream> #include<stdexcept> #include<exception> #include<string> #include<fstream> #include<thread> #include<boost/asio.hpp> #include<boost/system/error_code.hpp> #include<boost/system/system_error.hpp> usingnamespaceboost::asio; intmain() { io_serviceservice{}; ip::tcp::endpointend_point{ip::address::from_string("192.168.1.0"),80}; ip::tcp::socketsocket{service}; socket.open(ip::tcp::v4()); socket.connect(end_point); socket.write_some(buffer("GET/indexrn")); std::cout<<"socketavailable:"<<socket.available()<<std::endl; charthe_buffer[1024]{}; std::size_tsize{socket.read_some(buffer(the_buffer,1024))}; std::cout<<"sizeofreading:"<<size<<std::endl; socket.shutdown(ip::tcp::socket::shutdown_receive); socket.close(); std::cout<<the_buffer<<std::endl; return0; }5 (9).jpg

 

demo2:udpsocket

#include<iostream> #include<stdexcept> #include<exception> #include<string> #include<fstream> #include<thread> #include<boost/asio.hpp> #include<boost/system/error_code.hpp> #include<boost/system/system_error.hpp> usingnamespaceboost::asio; intmain() { io_serviceservice{}; ip::udp::endpointend_point_receiver{ip::address::from_string("192.168.1.0"),80}; ip::udp::socketsocket{service}; socket.open(ip::udp::v4()); socket.connect(end_point); charthe_buffer[1024]{}; socket.send_to(buffer("testn"),end_point_receiver);//senddatatospecifyaddress(theportis80). ip::udp::endpointend_point_sender{}; std::cout<<"thesenderaddress:"<<end_point_sender.address().to_string()<<std::endl; socket.receive_from(buffer(the_buffer,1024),end_point_sender); std::cout<<"receiveddata:"<<the_buffer<<std::endl; return0; }

demo3:查询域名ip地址.

#include<iostream> #include<stdexcept> #include<exception> #include<string> #include<fstream> #include<thread> #include<boost/asio.hpp> #include<boost/system/error_code.hpp> #include<boost/system/system_error.hpp> usingnamespaceboost::asio; intmain() { io_serviceservice{}; ip::tcp::resolverresolver{service}; ip::tcp::endpointend_point{}; ip::tcp::resolver::iteratorend_point_itr{resolver.resolve(ip::tcp::resolver::query("www.baidu.com","80"))}; std::cout<<end_point_itr->endpoint().address().to_string()<<std::endl; return0; }