Repository navigation
Expand file tree
/
Copy pathConnection.cpp
More file actions
216 lines (196 loc) · 7.82 KB
/
Copy pathConnection.cpp
File metadata and controls
216 lines (196 loc) · 7.82 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#include "Connection.h"
#include "Epoll.h"
#include <cerrno>
#include <cstdio>
#include <functional>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
/*
EventLoop *loop_; //Connection对应事件的循环 在构造函数中传入
std::unique_ptr<Socket> clientsock_; //与客户端通讯的Socket
std::unique_ptr<Channel> clientchannel_; //Connection对应的channel 在构造函数中创建
Buffer inputbuffer_; //接收缓冲区
Buffer outputbuffer_; //发送缓冲区
std::atomic_bool disconnect_; //客户端连接是否已断开 如果已断开 设置为true
std::function<void(spConnection)> closecallback_; //关闭fd_的回调函数 将回调TcpServer::closeconnection()
std::function<void(spConnection)> errorcallback_; //fd_发生错误的回调函数 将回调TcpServer::errorconnection()
std::function<void(spConnection,std::string&)> onmessagecallback_; //处理报文的回调函数 将回调TcpServer::onmessage()
std::function<void(spConnection)> sendcompletecallback_; //发送数据完成的回调函数 将回调TcpServer::sendcomplete()
Timestamp lastatime_; //时间戳 创建Connection对象时为当前时间 每接收一个报文 把时间戳更新为当前时间
*/
Connection::Connection(EventLoop *loop, std::unique_ptr<Socket> clientsock) // 传入的参数对应的EventLoop和客户端的fd
: loop_(loop), clientsock_(std::move(clientsock)),
clientchannel_(new Channel(loop_, clientsock_->fd())), disconnect_(false)
{
// 为新客户端连接准备读事件 注册放到start()里做
// 构造期间shared_ptr还没有建好 此时把fd加进epoll 别的线程可能立刻回调shared_from_this()
clientchannel_->setreadcallback(std::bind(&Connection::onmessage, this));
clientchannel_->setclosecallback(std::bind(&Connection::closecallback, this));
clientchannel_->seterrorcallback(std::bind(&Connection::errorcallback, this));
clientchannel_->setwritecallback(std::bind(&Connection::writecallback, this));
clientchannel_->useet(); // 客户端连上来的fd采用边缘触发
}
void Connection::start() // 在IO线程中注册读事件 必须在shared_ptr构造完成之后调用
{
clientchannel_->enablereading(); // 让epoll_wait()监视clientchannel的读事件
}
Connection::~Connection()
{
}
int Connection::fd() const // 返回客户端的fd
{
return clientsock_->fd();
}
std::string Connection::ip() const // 返回客户端的ip
{
return clientsock_->ip();
}
uint16_t Connection::port() const // 返回客户端的port
{
return clientsock_->port();
}
void Connection::onmessage() // 处理对端发送过来的信息
{
char buffer[1024];
while (true) // 由于使用非阻塞IO 一次读取buffer大小数据 直到全部的数据读取完毕
{
bzero(&buffer, sizeof(buffer));
ssize_t nread = read(fd(), buffer, sizeof(buffer));
if (nread > 0) // 如果成功读取到了数据
{
inputbuffer_.append(buffer, nread); // 把读取的数据追加到接收缓冲区中
}
else if (nread == -1 && errno == EINTR) // 读取数据的时候被信号中断 继续读取
{
continue;
}
else if (nread == -1 && ((errno == EAGAIN) || (errno == EWOULDBLOCK))) // 全部数据已读取完毕
{
std::string message;
while (true) // 从接收缓冲区中分析客户端的请求消息
{
if (inputbuffer_.pickmessage(message) == false)
break;
lastatime_ = Timestamp::now(); // 更新Connenction的时间戳
onmessagecallback_(shared_from_this(), message); // 回调TcpServer::onmessage()处理客户端的请求信息
}
break;
}
else if (nread == 0) // 客户端的连接已断开
{
closecallback(); // 回调TcpServer::closecallback()
break;
}
else // 其他错误 不能继续循环读 否则会空转
{
perror("read() failed");
errorcallback();
break;
}
}
}
void Connection::closecallback() // Tcp连接关闭的回调函数 供Channel回调
{
if (disconnect_.exchange(true)) // 已经处理过 防止重复回调
{
return;
}
clientchannel_->remove(); // 从事件循环中删除Channel
if (closecallback_)
{
closecallback_(shared_from_this()); // 回调TcpServer::closeconnection()
}
}
void Connection::errorcallback() // Tcp连接错误的回调函数 供Channel回调
{
if (disconnect_.exchange(true)) // 已经处理过 防止重复回调
{
return;
}
clientchannel_->remove(); // 从事件循环中删除Channel
if (errorcallback_)
{
errorcallback_(shared_from_this()); // 回调TcpServer::errorconnection()
}
}
void Connection::writecallback() // 处理写事件的回调函数 供Channel回调
{
// ET模式下要一次把数据写完 直到EAGAIN 不能只send一次
while (outputbuffer_.size() > 0)
{
ssize_t writen = ::send(fd(), outputbuffer_.data(), outputbuffer_.size(), MSG_NOSIGNAL);
if (writen > 0)
{
outputbuffer_.erase(0, writen); // 从outputbuffer_中删除已发送成功的字节数
continue;
}
if (writen == -1 && errno == EINTR)
{
continue;
}
if (writen == -1 && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
{
return; // 内核发送缓冲区已满 等下一次EPOLLOUT
}
perror("send() failed");
errorcallback(); // 发送失败 关闭连接
return;
}
// 如果发送缓冲区中没有数据了 表示数据已发送完成 不再关注写事件
clientchannel_->disablewriting();
if (sendcompletecallback_)
{
sendcompletecallback_(shared_from_this());
}
}
void Connection::setclosecallback(std::function<void(spConnection)> fn) // 设置关闭fd_的回调函数
{
closecallback_ = fn;
}
void Connection::seterrorcallback(std::function<void(spConnection)> fn)
{
errorcallback_ = fn;
}
void Connection::setonmessagecallback(std::function<void(spConnection, std::string &)> fn)
{
onmessagecallback_ = fn;
}
void Connection::setsendcompletecallback(std::function<void(spConnection)> fn)
{
sendcompletecallback_ = fn;
}
void Connection::send(const char *data, size_t size) // 发送数据 不管在任何线程中 都是调用此函数发送数据
{
if (disconnect_ == true)
{
printf("客户端连接已断开了,send()直接返回.\n");
return;
}
// 先拷贝一份数据 否则跨线程排队时传的是调用方栈上的指针 可能已经失效
std::string message(data, size);
if (loop_->isinloopthread()) // 判断当前线程是否为事件循环线程 即IO线程
{
// 如果当前线程是IO线程 直接调用sendinloop()发送数据
sendinloop(std::move(message));
}
else
{
// 如果当前线程不是IO线程 调用Eventloop::queueinloop() 把sendinloop()交给事件循环线程去执行
// 用shared_from_this()保证排队期间Connection不会被销毁
loop_->queueinloop(std::bind(&Connection::sendinloop, shared_from_this(), std::move(message)));
}
}
void Connection::sendinloop(std::string data) // 发送数据 如果当前线程是IO线程 直接调用此函数 如果是工作线程 将此函数传给IO线程去执行
{
if (disconnect_ == true)
{
return;
}
outputbuffer_.appendwithsep(data.data(), data.size()); // 把需要发送的数据保存到Connection的发送缓冲区
clientchannel_->enablewriting(); // 注册写事件
}
bool Connection::timeout(time_t now, int val) // 判断TCP连接是否超时(空闲太久)
{
return now - lastatime_.toint() > val;
}