1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| 【TcpServer 启动】 ↓ 1. TcpServer 构造 ├─ 创建 Acceptor(监听socket) └─ 创建 EventLoopThreadPool 线程池 ↓ 2. TcpServer::start() ├─ 启动IO线程池 └─ Acceptor::listen() 开启监听 + 绑定accept回调 ↓
【新连接到达】 3. 客户端连接 → 监听fd触发读事件 ↓ 4. Acceptor::handleAccept() ├─ accept 拿到 客户端connfd └─ 回调 TcpServer::newConnection ↓ 5. TcpServer::newConnection() ├─ 1. 分配ioLoop(轮询) ├─ 2. new 一个 TcpConnectionPtr(shared_ptr) ├─ 3. 存入 connections_ 容器管理 └─ 4. conn->connectEstablish(conn) 唤醒连接 ↓
【TcpConnection 连接初始化】 6. TcpConnection::connectEstablish() ├─ 修改状态为 kConnected ├─ channel_->tie(self) // weak_ptr 保生命周期 ├─ channel 绑定 读/写/关闭/错误回调 【绑定 shared_ptr self】 ├─ channel->enableReading() 注册读事件 └─ 执行 connectionCallback_(self) // 连接上线回调 ↓
【正常数据收发】 7. 客户端发数据 → connfd 读事件就绪 ↓ 8. Channel::handleEvent() → 触发 handleRead ↓ 9. TcpConnection::handleRead() ├─ Buffer 读取socket数据 └─ 执行 messageCallback_(self, buffer, time) // 业务消息回调 ↓
【连接关闭流程】 10. 客户端断开 / 异常 → 触发关闭事件 ↓ 11. TcpConnection::handleClose() ├─ 修改状态 ├─ 关闭channel事件监听 └─ 回调 TcpServer::removeConnection ↓ 12. TcpServer::removeConnection() └─ 扔到loop:removeConnectionInLoop ↓ 13. TcpServer::removeConnectionInLoop() ├─ connections_.erase(连接) // 解除server强引用 └─ ioLoop->queueInLoop(connectDestroy) ↓ 14. TcpConnection::connectDestroy() ├─ 下线回调 └─ channel 彻底移除poller ↓ 15. 所有shared_ptr引用释放 → TcpConnection 析构
|