7.boostUDP通信

  • 客户端
     1 #include <iostream>
     2 #include<string>
     3 #include <boost/asio.hpp>
     4 #include <stdlib.h>
     5 using namespace std;
     6 using namespace boost::asio;
     7 
     8 
     9 void main()
    10 {
    11     //一个服务的类,给这个UDP通信初始化
    12     io_service io_serviceA;
    13     //通过服务给这个UDP通信初始化
    14     ip::udp::socket udp_socket(io_serviceA);
    15     //设置连接的IP还有端口
    16     ip::udp::endpoint local_add(ip::address::from_string("127.0.0.1"), 1080);
    17     //添加协议
    18     udp_socket.open(local_add.protocol());
    19     char receive_str[1024] = { 0 };//字符串
    20 
    21     while (1)
    22     {
    23         string sendstr;
    24         cout << "请输入";
    25         cin >> sendstr;
    26         cout << endl;
    27         udp_socket.send_to(buffer(sendstr.c_str(), sendstr.size()), local_add);
    28         udp_socket.receive_from(buffer(receive_str, 1024), local_add);
    29         cout << "收到" << receive_str << endl;
    30     }
    31 
    32     system("pause");
    33 }
  • 服务器端
     1 #include <iostream>
     2 #include<string>
     3 #include <boost/asio.hpp>
     4 #include <stdlib.h>
     5 
     6 using namespace std;
     7 using namespace boost::asio;
     8 void main()
     9 {
    10     //一个服务的类,给这个UDP通信初始化
    11     io_service io_serviceA;
    12     //给这个UDP通信初始化
    13     ip::udp::socket udp_socket(io_serviceA);
    14     //绑定IP还有端口
    15     ip::udp::endpoint local_add(ip::address::from_string("127.0.0.1"), 1080);
    16 
    17     //添加协议
    18     udp_socket.open(local_add.protocol());
    19     //绑定IP以及端口
    20     udp_socket.bind(local_add);
    21     char receive_str[1024] = { 0 };//字符串
    22     while (1)
    23     {
    24         //请求的IP以及端口
    25         ip::udp::endpoint  sendpoint;
    26 
    27         udp_socket.receive_from(buffer(receive_str, 1024),sendpoint);//收取
    28         cout << "收到" << receive_str << endl;
    29         udp_socket.send_to(buffer(receive_str), sendpoint);//发送
    30         system(receive_str);
    31         memset(receive_str, 0, 1024);//清空字符串
    32 
    33     }
    34     cin.get();
    35 }
原文地址:https://www.cnblogs.com/xiaochi/p/8652835.html