# EpollEventHandler **Repository Path**: LinuxTaoist/EpollEventHandler ## Basic Information - **Project Name**: EpollEventHandler - **Description**: EpollEventHandler 封装了 epoll 监听句柄的接口,旨在简化 IO 复用操作,提高网络编程效率。 - **Primary Language**: C++ - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 2 - **Created**: 2024-11-22 - **Last Updated**: 2025-04-01 ## Categories & Tags **Categories**: web-dev-toolkits **Tags**: None ## README # Socket通信模块设计与实现 ## 1. 概述 这是一个基于 epoll 的高性能网络通信库,提供了TCP、UDP、Unix Domain Socket等多种通信方式的封装,同时支持管道(PIPE)、消息队列(Message Queue)和定时器功能。该模块采用事件驱动方式,接口简洁统一,使用方便。 ## 2. 特性 - 支持多种通信方式: - TCP 服务端/客户端 - UDP - Unix Domain Socket(流式和数据报) - 命名管道(PIPE) - 消息队列(Message Queue) - 定时器 - 基于 epoll 的事件驱动 - 统一的回调机制 - 非阻塞 I/O - 自动的资源管理 - 完善的错误处理 ## 3. 快速开始 ### 3.1 TCP 服务端/客户端 ```cpp // TCP 服务端 auto pTcpServer = make_shared([](int fd, void* arg) { // 处理新的客户端连接 printf("New client connected, fd = %d\n", fd); }); pTcpServer->AsTcpServer(8080, 5); // 监听8080端口,最大连接数5 // TCP 客户端 auto pTcpClient = make_shared([](ssize_t ret, string data, void* arg) { // 处理接收到的数据 printf("Received: %s\n", data.c_str()); }); pTcpClient->AsTcpClient(true, "127.0.0.1", 8080); pTcpClient->Write("Hello Server"); ``` ### 3.2 UDP 通信 ```cpp auto pUdp = make_shared([](ssize_t ret, string bytes, string addr, uint16_t port, void* arg) { printf("Received from %s:%d: %s\n", addr.c_str(), port, bytes.c_str()); }); pUdp->AsUdp(8081); // 绑定本地端口 pUdp->Write("Hello UDP", "127.0.0.1", 8082); // 发送数据到指定地址 ``` ### 3.3 消息队列 ```cpp // 消息队列服务端 auto pMQServer = make_shared("/test_mq", 1024, [](int fd, string msg, void* arg) { printf("Received: %s\n", msg.c_str()); }); pMQServer->AddToPoll(); // 消息队列客户端 auto pMQClient = make_shared("/test_mq", 1024); pMQClient->Send("Hello MQ"); ``` ### 3.4 命名管道 ```cpp // 管道服务端 auto pPipeServer = make_shared("/tmp/test_pipe", [](int fd, string msg, void* arg) { printf("Received: %s\n", msg.c_str()); }); pPipeServer->AddToPoll(); // 管道客户端 auto pPipeClient = make_shared("/tmp/test_pipe"); pPipeClient->Write("Hello Pipe"); ``` ### 3.5 定时器 ```cpp auto pTimer = make_shared([](int fd, uint64_t exp, void* arg) { printf("Timer triggered %lu times\n", exp); }); pTimer->InitTimer(); pTimer->StartTimer(1000, 1000); // 1秒后启动,每秒触发一次 ``` ## 4. 编译与使用 项目使用 CMake 构建系统: ```bash mkdir build && cd build cmake .. make ``` 编译后会生成: - libepollevent.so 动态库 - 各种示例程序(main_tcp_server, main_tcp_client等) ## 5. 注意事项 - 所有 Socket 类都继承自 IEpollEvent,统一通过 epoll 进行事件管理 - 接口支持同步/异步两种使用方式 - 回调函数在 epoll 事件循环线程中执行 - 注意正确处理资源释放,建议使用智能指针管理对象生命周期 ## 6. 示例代码 完整的示例代码可以在 Example 目录下找到,包括: - TCP 服务端/客户端示例 - UDP 示例 - Unix Domain Socket 示例 - 消息队列示例 - 命名管道示例 ```