且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

2Boost之UPD,Client and Server

更新时间:2022-09-03 09:03:28



客户端代码:

#include <iostream>

#include<string>

#include <boost/asio.hpp>

#include <stdlib.h>

 

using namespace std;

using namespace boost::asio;

 

void main()

{

    //一个服务的类,给这个UDP通信初始化

    io_service io_serviceA;

    //给这个UDP通信初始化

    ip::udp::socket udp_socket(io_serviceA);

    //绑定IP还有木马

    ip::udp::endpoint local_add(ip::address::from_string("127.0.0.1"), 1080);

 

    //添加协议

    udp_socket.open(local_add.protocol());

    //绑定IP以及端口

    //udp_socket.bind(local_add);

    //字符串

    char receive_str[1024] = { 0 };

 

    while (1)

    {

        string sendstr;

        cout << "请输入";

        cin >> sendstr;

        cout << endl;

        udp_socket.send_to(buffer(sendstr.c_str(), sendstr.size()), local_add);

        udp_socket.receive_from(buffer(receive_str, 1024), local_add);

        cout << "收到" << receive_str << endl;

    }

    system("pause");

}

运行截图:

2Boost之UPD,Client and Server

服务器端代码

#include <iostream>

#include<string>

#include <boost/asio.hpp>

#include <stdlib.h>

 

using namespace std;

using namespace boost::asio;

void main()

{

    //一个服务的类,给这个UDP通信初始化

    io_service io_serviceA;

    //给这个UDP通信初始化

    ip::udp::socket udp_socket(io_serviceA);

    //绑定IP还有木马

    ip::udp::endpoint local_add(ip::address::from_string("127.0.0.1"), 1080);

 

    //添加协议

    udp_socket.open(local_add.protocol());

   

    //绑定IP以及端口

    udp_socket.bind(local_add);

    //字符串

    char receive_str[1024] = { 0 };

    while (1)

    {

        //请求的IP以及端口

        ip::udp::endpoint  sendpoint;

 

        //收取

        udp_socket.receive_from(buffer(receive_str, 1024), sendpoint);

        cout << "收到" << receive_str << endl;

        //发送

        udp_socket.send_to(buffer(receive_str), sendpoint);

        system(receive_str);

        //清空字符串

        memset(receive_str, 0, 1024);

    }

    cin.get();

}

运行截图:

2Boost之UPD,Client and Server