server端代码:
#include <iostream> #include <boost/thread.hpp> #include <boost/asio.hpp> using namespace std; using namespace boost; void main() { boost::asio::io_service io_service; boost::asio::ip::udp::socket sock_srv(io_service); boost::asio::ip::udp::endpoint point_srv(boost::asio::ip::address::from_string("127.0.0.1"), 6000); sock_srv.open(point_srv.protocol()); sock_srv.bind(point_srv); while(1) { char buf[100] = {0}; boost::asio::ip::udp::endpoint point_conn; sock_srv.receive_from(boost::asio::buffer(buf, 100), point_conn); cout<<"server recv: "<<buf<<endl; sock_srv.send_to(boost::asio::buffer(buf), point_conn); } }
可改为:
#include <iostream> using namespace std; #include <boost/asio.hpp> int main(int argc, char*argv[]) { boost::asio::io_service io_service; // boost::asio::ip::udp::socket sock_srv(io_service); // // boost::asio::ip::udp::endpoint point_srv(boost::asio::ip::address::from_string("127.0.0.1"), 6000); // // sock_srv.open(point_srv.protocol()); // sock_srv.bind(point_srv); boost::asio::ip::udp::socket sock_srv(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 6000)); //recv char buf[100] = {0}; boost::asio::ip::udp::endpoint point_conn; sock_srv.receive_from(boost::asio::buffer(buf, 100), point_conn); cout<<"server recv:"<<buf<<endl; //send sock_srv.send_to(boost::asio::buffer(buf), point_conn); return 0; }
client端代码:
#include <iostream> #include <boost/thread.hpp> #include <boost/asio.hpp> using namespace std; using namespace boost; void main() { boost::asio::io_service io_service; boost::asio::ip::udp::socket sock_cli(io_service); boost::asio::ip::udp::endpoint point_srv(boost::asio::ip::address::from_string("127.0.0.1"), 6000); sock_cli.open(point_srv.protocol()); while(1) { sock_cli.send_to(boost::asio::buffer("hello world"), point_srv); char buf[100] = {0}; sock_cli.receive_from(boost::asio::buffer(buf, 100), point_srv); cout<<"client recv: "<<buf<<endl; } }
新代码:
#include <iostream> using namespace std; #include <boost/asio.hpp> int main(int argc, char*argv[]) { boost::asio::io_service io_service; boost::asio::ip::udp::socket sock_cli(io_service); sock_cli.open(boost::asio::ip::udp::v4()); //send boost::asio::ip::udp::resolver rlv(io_service); boost::asio::ip::udp::resolver::query qry(boost::asio::ip::udp::v4(), "127.0.0.1", "6000"); boost::asio::ip::udp::endpoint point_srv = *rlv.resolve(qry); sock_cli.send_to(boost::asio::buffer("hello world"), point_srv); //recv char buf[100] = {0}; boost::asio::ip::udp::endpoint point_conn; sock_cli.receive_from(boost::asio::buffer(buf, 100), point_conn); cout<<"client recv:"<<buf<<endl; return 0; }