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;
}
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

抓饼先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值