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

发布于:2025-02-15 ⋅ 阅读:(10) ⋅ 点赞:(0)

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

#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++ 编译器,编译命令如下:

g++ -std=c++17 -o udp_client udp_client.cpp -lpthread

运行程序:

./udp_client

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