c++ asio: udp server and client demo

一、server 端

  1. 创建udp::socket,用于收发数据
    1)需要创建一个io_context对象,初始化socket对象
    2)创建一个udp::endpoint对象,指定协议版本(v4,v6)和端口号,初始化socket对象

  2. 执行收发动作,socket.receive_from和socket.send_to
    1)收发都需要一个asio::buffer缓存。
    2)receive_from可以获取到client的endpoint,也可以用这个对象给client发送数据(send_to)

二、client 端

  1. 创建一个udp::socket对象,用于收发数据。
  2. 使用socket对象收发数据,socket.send_to和receive_from
    1)创建一个udp::endpoint对象,指定server端地址、端口。
#include <iostream>
#include <thread>
#include <boost/asio.hpp>

using namespace std;
using namespace boost;
using namespace boost::asio;
using asio::ip::udp;

void server_func() {
   
    io_context io;

    udp::socket server_socket(io, udp::endpoint(udp::v4(), 22333));

    int count = 1;
    while(true) {
   
        char buf[128] = {
   0};
        udp::endpoint client_endpoint;
        server_socket.receive_from(asio::buffer(buf), client_endpoint);

        printf("server -> [%d]: %s\n", count++, buf);
        cout << "server -> client info: " << client_endpoint.address() << ":" << client_endpoint.port() << endl;

        server_socket.send_to(asio::buffer("received from server"), client_endpoint);
    }
}

void client_func() {
   
    io_context io;
    udp::socket client_socket(io, udp::v4());

    udp::endpoint server_endpoint(ip::address::from_string("127.0.0.1"), 22333);

    while(true) {
   
        char buf[128] = {
   0};
        cout << "client -> input:\n";
        cin >> buf;

        client_socket.send_to(asio::buffer(buf), server_endpoint);

//        cout << "client -> get feedback from server: " << server_endpoint.address() << ":" << server_endpoint.port() << endl;
//        bzero(buf, 128);
        client_socket.receive_from(asio::buffer(buf), server_endpoint);
//        cout << "client -> " << buf << endl;
    }
}

int main() {
   
    jthread server(server_func);
    cout << "start server\n";

    jthread client(client_func);
    cout << "start client\n";

    return 0;
}

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-01-05 10:07:46       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-05 10:07:46       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-05 10:07:46       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-05 10:07:46       20 阅读

热门阅读

  1. uni-app 中使用定时器和取消定时器

    2024-01-05 10:07:46       36 阅读
  2. Invoke和BeginInvoke的区别

    2024-01-05 10:07:46       30 阅读
  3. SpringBoot之项目管理

    2024-01-05 10:07:46       38 阅读
  4. PAT乙级1038 统计同成绩学生

    2024-01-05 10:07:46       34 阅读
  5. 用python实现打飞机游戏

    2024-01-05 10:07:46       38 阅读
  6. 【C程序设计】C作用域

    2024-01-05 10:07:46       41 阅读
  7. 序列化与反序列化xml bin

    2024-01-05 10:07:46       37 阅读
  8. 好用的的抓包工具,Wireshark、whistle

    2024-01-05 10:07:46       51 阅读
  9. KNN 回归

    2024-01-05 10:07:46       36 阅读