独立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 端口监听,以便客户端能够正常通信。

相关推荐
侃侃_天下14 分钟前
最终的信号类
开发语言·c++·算法
博笙困了35 分钟前
AcWing学习——差分
c++·算法
echoarts40 分钟前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix1 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
青草地溪水旁1 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁1 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥1 小时前
C++ std::vector
c++
zl_dfq1 小时前
C++ 之【C++11的简介】(可变参数模板、lambda表达式、function\bind包装器)
c++
每天回答3个问题1 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
凯子坚持 c2 小时前
精通 Redis list:使用 redis-plus-plus 的现代 C++ 实践深度解析
c++·redis·list