请给出基于 ENet 的可靠通道封装

解读

国内大厂后端、游戏服务器、实时音视频岗位常把“在 UDP 之上做可靠通道”作为 C++ 面试分水岭。ENet 已经帮你解决了滑动窗口、重传、分片、连接管理,但面试官想看的不是你会不会调库,而是能否用现代 C++ 把 C 接口包成“线程安全、零拷贝、异常安全、可单元测试”的组件。
因此题目隐含考点:

  1. 资源所有权模型(谁 close peer、谁 destroy host)
  2. 跨线程调度(ENet 本身非线程安全)
  3. 非阻塞接口与异步回调如何转成 C++ Future/Promise
  4. 错误码如何转成 C++ 异常体系
  5. 零拷贝发送(const_buffer)与接收缓冲区复用

知识点

  • RAII 与智能指针定制 deleter(enet_host_destroy / enet_peer_reset)
  • 静态断言检查 ENet 版本
  • 单线程 EventLoop + 任务队列 避免锁
  • std::promise / std::future 实现异步 Connect/Send
  • const_buffer / mutable_buffer 抽象,支持 vector<string_view> 零拷贝拼装
  • 异常安全:ENet 函数失败后立即 RAII 清理,再抛 std::system_error
  • 单元测试桩:Host 可注入自定义 ENet-Callback 接口,实现离线测试

答案

// 仅头文件示例,生产需拆 .h/.cpp
#pragma once
#include <enet/enet.h>
#include <vector>
#include <memory>
#include <system_error>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
#include <spdlog/spdlog.h>

namespace net {

class ENetException : public std::system_error {
public:
    explicit ENetException(int enet_err)
        : std::system_error(enet_err, std::generic_category(),
                            "ENet error: " + std::to_string(enet_err)) {}
};

inline void throwOnErr(int rc) {
    if (rc < 0) throw ENetException(rc);
}

// 零拷贝 buffer 视图
using Buffer = std::vector<std::string_view>;

// 前向声明
class Peer;

class Host {
public:
    // io_service 模式:单线程事件循环
    explicit Host(size_t maxPeers = 32, enet_uint16 port = 0)
        : work_(true) {
        ENetAddress addr{ENET_HOST_ANY, port};
        host_.reset(enet_host_create(&addr, maxPeers, 2, 0, 0));
        if (!host_) throw std::bad_alloc();
        loop_ = std::thread([this] { eventLoop(); });
    }
    ~Host() {
        work_ = false;
        enet_host_interrupt(host_.get()); // 打断 enet_host_service
        if (loop_.joinable()) loop_.join();
    }
    // 异步连接
    std::shared_ptr<Peer> connect(const char* ip, enet_uint16 port);
    // 停止接受新连接
    void stop() { work_ = false; }
private:
    void eventLoop();
    std::unique_ptr<ENetHost, decltype(&enet_host_destroy)> host_{nullptr, enet_host_destroy};
    std::atomic<bool> work_;
    std::thread loop_;
    std::mutex mq_mut_;
    std::queue<std::function<void()>> mq_; // 跨线程任务队列
};

class Peer : public std::enable_shared_from_this<Peer> {
public:
    ~Peer() {
        if (peer_) {
            enet_peer_disconnect(peer_, 0);
            // 等待超时后强制 reset;生产环境可再优化
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            enet_peer_reset(peer_);
        }
    }
    // 异步发送
    std::future<void> sendReliable(Buffer buf) {
        auto prom = std::make_shared<std::promise<void>>();
        host_.mq_.emplace([self = shared_from_this(), buf, prom]() {
            ENetPacket* pkt = enet_packet_create(nullptr, 0, ENET_PACKET_FLAG_RELIABLE);
            if (!pkt) { prom->set_exception(std::make_exception_ptr(std::bad_alloc())); return; }
            size_t total = 0;
            for (auto s : buf) total += s.size();
            enet_packet_resize(pkt, total);
            char* dst = reinterpret_cast<char*>(pkt->data);
            for (auto s : buf) {
                std::memcpy(dst, s.data(), s.size());
                dst += s.size();
            }
            int rc = enet_peer_send(self->peer_, 0, pkt);
            if (rc < 0) {
                enet_packet_destroy(pkt);
                prom->set_exception(std::make_exception_ptr(ENetException(rc)));
            } else {
                prom->set_value();
            }
        });
        enet_host_interrupt(host_.host_.get()); // 打断阻塞
        return prom->get_future();
    }
private:
    friend class Host;
    Peer(Host& h, ENetPeer* p) : host_(h), peer_(p) {}
    Host& host_;
    ENetPeer* peer_ = nullptr;
};

std::shared_ptr<Peer> Host::connect(const char* ip, enet_uint16 port) {
    ENetAddress addr;
    enet_address_set_host(&addr, ip);
    addr.port = port;
    auto prom = std::make_shared<std::promise<std::shared_ptr<Peer>>>();
    auto fut = prom->get_future();
    mq_.emplace([this, addr, prom]() {
        ENetPeer* raw = enet_host_connect(host_.get(), &addr, 2, 0);
        if (!raw) {
            prom->set_exception(std::make_exception_ptr(std::runtime_error("connect failed")));
            return;
        }
        auto p = std::shared_ptr<Peer>(new Peer(*this, raw));
        // 等待 CONNECT 事件确认,简化:直接返回
        prom->set_value(p);
    });
    enet_host_interrupt(host_.get());
    return fut.get();
}

void Host::eventLoop() {
    ENetEvent ev;
    while (work_) {
        while (enet_host_service(host_.get(), &ev, 0) > 0) {
            switch (ev.type) {
            case ENET_EVENT_TYPE_CONNECT:
                spdlog::info("new peer");
                break;
            case ENET_EVENT_TYPE_RECEIVE:
                enet_packet_destroy(ev.packet);
                break;
            default:
                break;
            }
        }
        // 处理跨线程任务
        std::function<void()> task;
        {
            std::lock_guard<std::mutex> lk(mq_mut_);
            if (!mq_.empty()) {
                task = std::move(mq_.front());
                mq_.pop();
            }
        }
        if (task) task();
        std::this_thread::sleep_for(std::chrono::microseconds(100));
    }
}

} // namespace net

要点回顾:

  • Host 与 Peer 均为 RAII,资源释放顺序可控
  • 所有 ENet 调用集中在单线程 EventLoop,通过任务队列实现线程安全
  • sendReliable 返回 std::future,方便上层用协程或 async 链式调用
  • Buffer 采用 string_view 实现零拷贝拼装,避免额外 malloc

拓展思考

  1. 性能调优:ENet 的带宽阈值与 RTT 计算对游戏手感影响极大,可暴露 enet_host_bandwidth_limit 到配置中心,热更新而不重启进程。
  2. 加密需求:国内版号合规要求数据加密,可在 ENet 之上插入 sodium/libsodium 的 box 机制,在 CONNECT 阶段交换临时公钥,对 payload 进行 ChaCha20-Poly1305 加密,注意先加密再分片,避免重放。
  3. 多核扩展:单线程 EventLoop 在 100k 并发下会成为瓶颈,可借鉴 SO_REUSEPORT 启动多个 Host 实例,一致性哈希将 fd 分到不同线程,但需解决跨线程迁移 Peer 的状态机同步问题。
  4. 测试策略:使用 TC_PRE/POST 钩子注入丢包、延迟、乱序,结合 GoogleTest + gmock 断言重传次数与 RTT 估算是否符合预期,量化面试答案的可靠性。