muduo.drawio

核心事件流转完整流程图(从监听连接到数据收发)

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
启动TcpServer


创建Acceptor → 绑定baseLoop(主EventLoop) → 创建listenfd → socket/bind/listen


Acceptor创建AcceptorChannel(绑定listenfd) → 注册到baseLoop的Poller


baseLoop进入EventLoop::loop() → Poller调用epoll_wait监听listenfd的可读事件


客户端发起连接 → listenfd触发可读事件


Poller将AcceptorChannel加入activeChannels_ → EventLoop处理Channel回调


Acceptor执行accept() → 获取新连接connfd → 创建TcpConnection实例


TcpConnection创建Socket(封装connfd)、ConnectionChannel(绑定connfd)


通过EventLoopThreadPool轮询getNextLoop() → 选择一个subLoop(从EventLoop)


将ConnectionChannel注册到subLoop的Poller → subLoop监听connfd的读写事件


TcpConnection维护发送/接收Buffer → 数据流转:
应用数据 → Buffer → TCP发送缓冲区 → send()
recv() → TCP接收缓冲区 → Buffer → 应用数据


TcpServer维护connections_,管理所有TcpConnection实例

关键模块关系明细

1. Reactor 核心链(EventLoop → Poller → Channel)

1
2
3
4
5
6
7
8
EventLoop (Reactor)
├─ poller_ (Poller/EPollPoller)
│ └─ channels_ (unordered_map<int, Channel*>)
│ ├─ AcceptorChannel (listenfd,主loop持有)
│ └─ ConnectionChannel (connfd,subLoop持有)
├─ activeChannels_ (本次事件循环的活跃Channel列表)
├─ wakeupFd / wakeupChannel (跨线程唤醒EventLoop)
└─ 绑定线程: one loop per thread (EventLoopThread)

2. 连接管理链(TcpServer → Acceptor → TcpConnection)

1
2
3
4
5
6
7
8
9
10
11
TcpServer
├─ Acceptor (主loop持有,监听新连接)
│ └─ 触发accept() → 创建TcpConnection
├─ EventLoopThreadPool (管理多个subLoop)
│ └─ 轮询分配subLoop给新连接
└─ connections_ (存储所有TcpConnection)
└─ 每个TcpConnection对应一个客户端连接
├─ Socket (封装connfd)
├─ ConnectionChannel (注册到subLoop)
├─ 发送Buffer
└─ 接收Buffer

3. 缓冲区数据链路(Buffer)

1
2
3
4
5
6
7
8
9
10
11
12
13
应用层数据
↓ (写入)
Buffer (prependable空间 + readeridx + writeridx)
↓ (写入)
TCP内核发送缓冲区
↓ (系统调用)
send() → 网络传输
↓ (对端接收)
TCP内核接收缓冲区
↓ (读取)
Buffer
↓ (读取)
应用层数据
模块 核心职责 关键成员 / 操作
Channel 事件通道,封装 fd 与回调 fd、events、revents、callbacks;分 AcceptorChannel/ConnectionChannel
Poller/EPollPoller I/O 多路复用,事件分发 unordered_map<int, Channel*> channels;epoll_wait 监听事件
EventLoop Reactor 核心,事件循环 activeChannels_、poller_、wakeupFd、wakeupChannel;loop () 循环
EventLoopThread 线程封装,绑定 EventLoop one loop per thread
EventLoopThreadPool 线程池,轮询分配 loop getNextLoop () 轮询算法
Socket 封装 socket 操作 封装 connfd 的 bind/listen/connect 等
Acceptor 监听新连接 封装 listenfd;socket/bind/listen;绑定 baseLoop
Buffer 应用层缓冲区 prependable、readeridx、writeridx;数据中转
TcpConnection 客户端连接实例 每个连接对应一个实例;持有 Socket/Channel/Buffer/ 回调
TcpServer 服务端入口 持有 Acceptor / 线程池;管理所有 TcpConnection