-
Notifications
You must be signed in to change notification settings - Fork 0
/
Channel.cpp
105 lines (94 loc) · 2.46 KB
/
Channel.cpp
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include "Channel.h"
#include <sys/epoll.h>
#include "EventLoop.h"
#include "Logger.h"
using namespace simple_muduo;
// 静态变量需要在cpp中初始化
const int Channel::kNoneEvent = 0;
const int Channel::kReadEvent = EPOLLIN | EPOLLPRI;
const int Channel::kWriteEvent = EPOLLOUT;
Channel::Channel(EventLoop* loop, int fd)
: loop_(loop)
, fd_(fd)
, events_(0)
, revents_(0)
, index_(-1)
, tied_(false)
{
}
Channel::~Channel()
{
}
// channel的tie方法什么时候调用过-----TcpConnection====> channel
// TcpConnection中注册了Chnanel对应的回调函数,传入的回调函数均为TcpConnection
// 对象的成员方法,因此可以说明一点就是:Channel的结束一定早于TcpConnection对象!
// 此处用tie去解决TcoConnection和Channel的生命周期时长问题,从而保证了Channel对
// 象能够在TcpConnection销毁前销毁。
void Channel::tie(const std::shared_ptr<void> & obj)
{
tie_ = obj;
tied_ = true;
}
// Channel管理的fd的events事件改编后,update负责在poller里面更改fd相应的事件epoll_ctl
void Channel::update()
{
// 通过channel所属的eventloop,调用poller的相应方法,注册fd的events事件
loop_->updateChannel(this);
}
// 在channel所属的EventLoop中把当前的channel删除掉
void Channel::remove()
{
loop_->removeChannel(this);
}
void Channel::handleEvent(Timestamp receiveTime)
{
if (tied_)
{
std::shared_ptr<void> guard = tie_.lock();
if (guard)
{
handleEventWithGuard(receiveTime);
}
// 如果提升失败了 就不做任何处理 说明Channel的TcpConnection对象已经不存在了
}
else
{
handleEventWithGuard(receiveTime);
}
}
void Channel::handleEventWithGuard(Timestamp receiveTime)
{
LOG_INFO("channel handleEvent revents:%d\n", revents_);
// 关闭
if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN)) // 当TcpConnection对应Channel 通过shutdown 关闭写端 epoll触发EPOLLHUP
{
if (closeCallback_)
{
closeCallback_();
}
}
// 错误
if (revents_ & EPOLLERR)
{
if (errorCallback_)
{
errorCallback_();
}
}
// 读
if (revents_ & (EPOLLIN | EPOLLPRI))
{
if (readCallback_)
{
readCallback_(receiveTime);
}
}
// 写
if (revents_ & EPOLLOUT)
{
if (writeCallback_)
{
writeCallback_();
}
}
}