Skip to content

NET_TcpServer

SweerItTer edited this page Feb 21, 2026 · 1 revision

TcpServer

概述

TcpServer 是 TCP 服务器的核心类,负责服务器的生命周期管理和全局调度。专注连接管理和数据传输,命令处理由 CommandHandler 模块负责。

类定义

class TcpServer : public std::enable_shared_from_this<TcpServer> {
public:
    explicit TcpServer(const TcpServerConfig& config = TcpServerConfig(),
                      std::weak_ptr<CommandHandler> commandHandler = {});
    ~TcpServer();

    // 禁止拷贝,允许移动
    TcpServer(const TcpServer&) = delete;
    TcpServer& operator=(const TcpServer&) = delete;
    TcpServer(TcpServer&& other) noexcept;
    TcpServer& operator=(TcpServer&& other) noexcept;

    // 命令处理器设置
    void setCommandHandler(std::shared_ptr<CommandHandler> commandHandler) noexcept;
    std::weak_ptr<CommandHandler> getCommandHandler() const noexcept;

    // 服务器控制
    bool start();
    void stop();
    bool isRunning() const noexcept;

    // 数据发送
    bool sendToClient(uint64_t clientId, const DataPacket& packet);
    size_t broadcast(const DataPacket& packet);

    // 状态查询
    size_t getClientCount() const noexcept;
    const TcpServerConfig& getConfig() const noexcept;
};

公共方法

构造/析构

TcpServer(const TcpServerConfig& config, std::weak_ptr commandHandler)

描述: 构造 TCP 服务器。

参数:

  • config: 服务器配置
  • commandHandler: 命令处理器弱引用(可选,使用 weak_ptr 避免所有权问题)

注意: TcpServer 必须被 shared_ptr 管理,因为内部使用 shared_from_this() 获取服务器实例。

示例:

TcpServerConfig config;
config.port = 8080;

// 创建命令处理器
auto commandHandler = std::make_shared<CommandHandler>();
commandHandler->registerCommand("ECHO", [](uint64_t clientId, auto, const std::string& params) {
    return params;
});

// 创建服务器并设置命令处理器
// 注意:必须使用 shared_ptr 管理
auto server = std::make_shared<TcpServer>(config, commandHandler);
server->start();

~TcpServer()

描述: 析构函数,自动停止服务器并清理资源。

服务器控制

bool start()

描述: 启动服务器(非阻塞)。

返回值:

  • true: 启动成功
  • false: 启动失败

异常: TcpException - 启动失败时抛出

示例:

if (server.start()) {
    std::cout << "Server started" << std::endl;
}

void stop()

描述: 停止服务器(阻塞,等待所有连接关闭)。

示例:

server.stop();

bool isRunning() const noexcept

描述: 检查服务器是否运行中。

返回值:

  • true: 运行中
  • false: 已停止

命令处理器设置

void setCommandHandler(std::shared_ptr commandHandler) noexcept

描述: 设置命令处理器。

参数:

  • commandHandler: 命令处理器智能指针

示例:

auto commandHandler = std::make_shared<CommandHandler>();
server.setCommandHandler(commandHandler);

std::weak_ptr getCommandHandler() const noexcept

描述: 获取命令处理器弱引用。

返回值: 命令处理器弱引用

示例:

auto weakHandler = server.getCommandHandler();
if (auto handler = weakHandler.lock()) {
    // 使用 handler
}

数据发送

bool sendToClient(uint64_t clientId, const DataPacket& packet)

描述: 向指定客户端发送数据(同步)。

参数:

  • clientId: 客户端 ID
  • packet: 数据包

返回值:

  • true: 发送成功
  • false: 发送失败

示例:

DataPacket pkt = DataPacket::createText("Hello");
server.sendToClient(clientId, pkt);

size_t broadcast(const DataPacket& packet)

描述: 向所有客户端发送数据(同步)。

参数:

  • packet: 数据包

返回值: 成功发送的客户端数量

示例:

size_t sent = server.broadcast(DataPacket::createText("Broadcast message"));

状态查询

size_t getClientCount() const noexcept

描述: 获取当前连接的客户端数量。

返回值: 客户端数量

const TcpServerConfig& getConfig() const noexcept

描述: 获取服务器配置。

返回值: 配置对象引用

配置选项

TcpServerConfig

struct TcpServerConfig {
    uint16_t port{8080};                    // 监听端口
    std::string bindAddress{"0.0.0.0"};     // 绑定地址
    size_t maxClients{64};                  // 最大客户端连接数
    size_t threadPoolMin{2};                // 线程池最小线程数
    size_t threadPoolMax{8};                // 线程池最大线程数
    size_t maxQueueSize{128};               // 任务队列最大长度
    size_t receiveBufferSize{4096};         // 接收缓冲区大小
    bool enableKeepAlive{true};             // 启用 TCP Keep-Alive
    int keepAliveIdle{60};                  // Keep-Alive 空闲时间(秒)
    int keepAliveInterval{10};              // Keep-Alive 探测间隔(秒)
    int keepAliveCount{5};                  // Keep-Alive 探测次数
};

使用场景

场景 1: 基本 TCP 服务器

TcpServerConfig config;
config.port = 8080;

// 创建命令处理器
auto commandHandler = std::make_shared<CommandHandler>();
commandHandler->registerCommand("ECHO", [](uint64_t clientId, auto, const std::string& params) {
    return params;
});

// 创建服务器(必须使用 shared_ptr 管理)
auto server = std::make_shared<TcpServer>(config, commandHandler);
server->start();

场景 2: DMA-BUF 零拷贝服务器

auto commandHandler = std::make_shared<CommandHandler>();

commandHandler->registerCommand("GET_FRAME", [&](uint64_t clientId, auto, const std::string& params) {
    // 获取摄像头帧
    auto frame = camera->getFrame();
    DmaBufferPtr dmabuf = frame->getDmaBuffer();

    // 零拷贝发送
    server->sendToClient(clientId, DataPacket::createDmaBuf(dmabuf));

    return "OK";
});

auto server = std::make_shared<TcpServer>(config, commandHandler);
server->start();

场景 3: 广播服务器

TcpServer server(config, nullptr);  // 不使用命令处理器

// 向所有客户端广播数据
server.broadcast(DataPacket::createText("Server message"));

线程安全

所有公共方法都是线程安全的,可以在多个线程中同时调用。

注意事项

  1. 生命周期: TcpServer 必须被 shared_ptr 管理,因为内部使用 shared_from_this() 获取服务器实例
  2. 命令处理器: 命令处理委托给 CommandHandler,使用 weak_ptr 避免所有权问题
  3. 资源清理: stop() 是阻塞的,会等待所有连接关闭
  4. 连接管理: 客户端连接由 TcpServer 内部管理,使用工厂函数 createConnection() 创建

架构设计

┌─────────────────────────────────────────────────────────┐
│                      TcpServer                          │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │ 连接管理    │  │ 数据传输    │  │ 命令委托    │     │
│  │ acceptLoop  │  │ sendToClient│  │ executeCmd  │     │
│  │ handleClient│  │ broadcast   │  │ ->Handler   │     │
│  │ createConn  │  │             │  │             │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
└─────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────┐
│                    SocketConnection                     │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │ 接收循环    │  │ 发送循环    │  │ 命令委托    │     │
│  │ receiveLoop │  │ sendLoop    │  │ ->Server    │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
└─────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────┐
│                    CommandHandler                       │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │ 注册表      │  │ 分发逻辑    │  │ 回调执行    │     │
│  │ registerCmd │  │ executeCmd  │  │ callback()  │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
└─────────────────────────────────────────────────────────┘

架构设计

┌─────────────────────────────────────────────────────────┐
│                      TcpServer                          │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │ 连接管理    │  │ 数据传输    │  │ 命令委托    │     │
│  │ acceptLoop  │  │ sendToClient│  │ executeCmd  │     │
│  │ handleClient│  │ broadcast   │  │ ->Handler   │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
└─────────────────────────────────────────────────────────┘
                           │
                           ▼
┌─────────────────────────────────────────────────────────┐
│                    CommandHandler                       │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐     │
│  │ 注册表      │  │ 分发逻辑    │  │ 回调执行    │     │
│  │ registerCmd │  │ executeCmd  │  │ callback()  │     │
│  └─────────────┘  └─────────────┘  └─────────────┘     │
└─────────────────────────────────────────────────────────┘

相关类

主页

API 文档

DMA 模块

DRM 模块

NET 模块

V4L2 模块

V4L2Param 模块

RGA 模块

MPP 模块

Sys 模块

Mouse 模块

Utils 模块

Clone this wiki locally