-
Notifications
You must be signed in to change notification settings - Fork 1
NET_TcpServer
SweerItTer edited this page Feb 21, 2026
·
1 revision
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;
};描述: 构造 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();描述: 析构函数,自动停止服务器并清理资源。
描述: 启动服务器(非阻塞)。
返回值:
-
true: 启动成功 -
false: 启动失败
异常: TcpException - 启动失败时抛出
示例:
if (server.start()) {
std::cout << "Server started" << std::endl;
}描述: 停止服务器(阻塞,等待所有连接关闭)。
示例:
server.stop();描述: 检查服务器是否运行中。
返回值:
-
true: 运行中 -
false: 已停止
描述: 设置命令处理器。
参数:
-
commandHandler: 命令处理器智能指针
示例:
auto commandHandler = std::make_shared<CommandHandler>();
server.setCommandHandler(commandHandler);描述: 获取命令处理器弱引用。
返回值: 命令处理器弱引用
示例:
auto weakHandler = server.getCommandHandler();
if (auto handler = weakHandler.lock()) {
// 使用 handler
}描述: 向指定客户端发送数据(同步)。
参数:
-
clientId: 客户端 ID -
packet: 数据包
返回值:
-
true: 发送成功 -
false: 发送失败
示例:
DataPacket pkt = DataPacket::createText("Hello");
server.sendToClient(clientId, pkt);描述: 向所有客户端发送数据(同步)。
参数:
-
packet: 数据包
返回值: 成功发送的客户端数量
示例:
size_t sent = server.broadcast(DataPacket::createText("Broadcast message"));描述: 获取当前连接的客户端数量。
返回值: 客户端数量
描述: 获取服务器配置。
返回值: 配置对象引用
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 探测次数
};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();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();TcpServer server(config, nullptr); // 不使用命令处理器
// 向所有客户端广播数据
server.broadcast(DataPacket::createText("Server message"));所有公共方法都是线程安全的,可以在多个线程中同时调用。
-
生命周期:
TcpServer必须被shared_ptr管理,因为内部使用shared_from_this()获取服务器实例 -
命令处理器: 命令处理委托给 CommandHandler,使用
weak_ptr避免所有权问题 - 资源清理: stop() 是阻塞的,会等待所有连接关闭
-
连接管理: 客户端连接由 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() │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────┘
- SocketConnection - Socket 连接
- CommandHandler - 命令处理器
- DataPacket - 数据包类型
- TcpException - 异常类
主页
API 文档
DMA 模块
DRM 模块
- DRM 模块总览
- DeviceController - DRM 设备控制器
- DrmLayer - DRM 图层管理
- PlanesCompositor - DRM 平面合成器
- DrmBpp - DRM 格式定义
NET 模块
- NET 模块总览
- TcpServer - TCP 服务器
- SocketConnection - Socket 连接管理
- CommandHandler - 命令处理器
- DataPacket - 数据包
V4L2 模块
- V4L2 模块总览
- CameraController - V4L2 摄像头控制器
- Frame - V4L2 帧数据结构
- FormatTool - V4L2 格式工具
- Exception - V4L2 异常类
V4L2Param 模块
- V4L2Param 模块总览
- ParamControl - 参数控制
- ParamLogger - 参数日志
- ParamProcessor - 参数处理器
RGA 模块
- RGA 模块总览
- RgaConverter - RGA 转换器
- RgaProcessor - RGA 处理器
- FormatTool - RGA 格式工具
MPP 模块
- MPP 模块总览
- EncoderContext - 编码器上下文
- EncoderCore - 编码器核心
- JpegEncoder - JPEG 编码器
- StreamWriter - 流写入器
- MppResourceGuard - MPP 资源守护
- FileTools - 文件工具
- FormatTool - 格式工具
Sys 模块
- Sys 模块总览
- CpuMonitor - CPU 监控器
- MemoryMonitor - 内存监控器
- Base - 基础类
Mouse 模块
- Mouse 模块总览
- Watcher - 鼠标监视器
Utils 模块
- Utils 模块总览
- AsyncThreadPool - 异步线程池
- ConcurrentQueue - 并发队列
- FdWrapper - 文件描述符包装器
- FenceWatcher - 围栏监视器
- FixedSizePool - 固定大小对象池
- Logger - 日志记录器
- ObjectsPool - 对象池
- OrderedQueue - 有序队列
- ProgressBar - 进度条
- SafeQueue - 安全队列
- SharedBufferState - 共享缓冲区状态
- SimpleVariant - 简单变体类型
- ThreadPauser - 线程暂停器
- ThreadUtils - 线程工具
- Types - 类型定义
- UdevMonitor - Udev 监视器