独立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.112345 端口。
  • 定义要发送的消息并调用 sendMessage 方法发送。
  • 调用 receiveMessage 方法接收服务器的响应并输出。
  • 使用 try-catch 块捕获并处理可能的异常。

编译和运行

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

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

运行程序:

sh 复制代码
./udp_client

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

相关推荐
Chef_Chen17 分钟前
从0开始学习R语言--Day39--Spearman 秩相关
开发语言·学习·r语言
不学会Ⅳ25 分钟前
Mac M芯片搭建jdk源码环境(jdk24)
java·开发语言·macos
2401_8812444028 分钟前
牛客周赛99
c++
好开心啊没烦恼1 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas
lljss20202 小时前
Python11中创建虚拟环境、安装 TensorFlow
开发语言·python·tensorflow
山登绝顶我为峰 3(^v^)33 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Python×CATIA工业智造5 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
游戏开发爱好者86 小时前
iOS重构期调试实战:架构升级中的性能与数据保障策略
websocket·网络协议·tcp/ip·http·网络安全·https·udp
十五年专注C++开发6 小时前
CMake基础:条件判断详解
c++·跨平台·cmake·自动化编译
我叫小白菜6 小时前
【Java_EE】单例模式、阻塞队列、线程池、定时器
java·开发语言