独立C++ asio库实现的UDP Client

以下是使用独立的 asio 库(无需依赖 Boost)实现的 UDP 客户端示例代码。该客户端可以向指定的 UDP 服务器发送消息,并接收服务器的响应。

cpp 复制代码
#include <iostream>
#include <asio.hpp>
#include <asio/ip/udp.hpp>
#include <string>
#include <array>

class UdpClient {
public:
    UdpClient(asio::io_context& io_context, const std::string& server_ip, const std::string& server_port)
        : socket_(io_context), resolver_(io_context) {
        // 创建查询对象
        asio::ip::udp::resolver::query query(asio::ip::udp::v4(), server_ip, server_port);
        // 解析服务器地址和端口,获取端点信息
        auto endpoints = resolver_.resolve(query);
        // 选择第一个解析结果作为目标端点
        receiver_endpoint_ = *endpoints.begin();
        // 打开 UDP 套接字
        socket_.open(asio::ip::udp::v4());
    }

    void sendMessage(const std::string& message) {
        // 发送消息到服务器
        socket_.send_to(asio::buffer(message), receiver_endpoint_);
    }

    std::string receiveMessage() {
        std::array<char, 1024> buffer;
        asio::ip::udp::endpoint sender_endpoint;
        // 接收服务器的响应
        size_t length = socket_.receive_from(asio::buffer(buffer), sender_endpoint);
        return std::string(buffer.data(), length);
    }

private:
    asio::ip::udp::socket socket_;
    asio::ip::udp::resolver resolver_;
    asio::ip::udp::endpoint receiver_endpoint_;
};

int main() {
    try {
        asio::io_context io_context;
        // 创建 UDP 客户端,连接到本地 127.0.0.1 的 12345 端口
        UdpClient client(io_context, "127.0.0.1", "12345");

        // 要发送的消息
        std::string message = "Hello, UDP Server!";
        client.sendMessage(message);

        // 接收服务器的响应
        std::string response = client.receiveMessage();
        std::cout << "Received from server: " << response << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}

代码说明

UdpClient 类
  1. 构造函数 :
    • 接收 asio::io_context 对象、服务器 IP 地址和端口号作为参数。
    • 创建 asio::ip::udp::resolver::query 对象,用于解析服务器地址和端口。
    • 调用 resolver_.resolve(query) 进行解析,获取服务器端点信息。
    • 选择第一个解析结果作为目标端点 receiver_endpoint_。
    • 打开 UDP 套接字。
  2. sendMessage 方法 :
    • 接收一个 std::string 类型的消息,将其转换为 asio::buffer 并发送到服务器端点。
  3. receiveMessage 方法 :
    • 创建一个 std::array 作为接收缓冲区。
    • 调用 socket_.receive_from 接收服务器的响应,并记录发送方的端点信息。
    • 将接收到的数据转换为 std::string 并返回。
main 函数
  • 创建 asio::io_context 对象。
  • 创建 UdpClient 实例,连接到本地 127.0.0.1 的 12345 端口。
  • 定义要发送的消息并调用 sendMessage 方法发送。
  • 调用 receiveMessage 方法接收服务器的响应并输出。
  • 使用 try-catch 块捕获并处理可能的异常。

编译和运行

假设使用 g++ 编译器,编译命令如下:

sh 复制代码
g++ -std=c++17 -o udp_client udp_client.cpp -lpthread

运行程序:

sh 复制代码
./udp_client

请确保有一个 UDP 服务器在 127.0.0.1 的 12345 端口监听,以便客户端能够正常通信。

相关推荐
YSL0701248 分钟前
一文通关-----栈和队列
开发语言·数据结构
维克兜率天18 分钟前
【维克】统计套利建模:从因子到信号的完整流程
android·开发语言·python·算法·kotlin
Pin_Qing23 分钟前
同一天,谷歌半价卖旗舰,阶跃翻倍收缓存
大数据·开发语言·人工智能·程序人生·缓存
2501_9307077828 分钟前
使用C#代码在 Word 文档中添加、插入或删除页面
开发语言·c#·word
没有梦想的咸鱼185-1037-166332 分钟前
从通量数据到SCI论文——AI-R语言生态系统碳水热通量及其机制分析与论文
开发语言·人工智能·数据分析·r语言
weixin_4617694038 分钟前
conda create 创建容器 Failed to resolve ‘repo.anaconda.com‘问题
开发语言·python·conda·repo·网络问题·无法创建
Want59539 分钟前
Python生日蛋糕
开发语言·python
垆边人似月.40 分钟前
找出最小的 K 个数
数据结构·c++·算法
C语言小火车1 小时前
C++ 为什么越来越依赖标准库?
java·开发语言·c++
郝学胜-神的一滴1 小时前
金融数据分析实战:从数据清洗到策略回测,Python全链路落地
开发语言·python·程序人生·金融·数据挖掘·数据分析