-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver.cpp
286 lines (261 loc) · 7.41 KB
/
webserver.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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// encode UTF-8
// @Author : Aged_cat
// @Date : 2021-05-21
#include "webserver.h"
WebServer::WebServer(
int port,int trigMode,int timeoutMS,bool optLinger,int threadNum):
port_(port),openLinger_(optLinger),timeoutMS_(timeoutMS),isClose_(false),
timer_(new TimerManager()),threadpool_(new ThreadPool(threadNum)),epoller_(new Epoller())
{
//获取当前工作目录的绝对路径
srcDir_=getcwd(nullptr,256);
assert(srcDir_);
//拼接字符串
strncat(srcDir_,"/resources/",16);
HTTPconnection::userCount=0;
HTTPconnection::srcDir=srcDir_;
initEventMode_(trigMode);
if(!initSocket_()) isClose_=true;
}
WebServer::~WebServer()
{
close(listenFd_);
isClose_=true;
free(srcDir_);
}
void WebServer::initEventMode_(int trigMode) {
listenEvent_ = EPOLLRDHUP;
connectionEvent_ = EPOLLONESHOT | EPOLLRDHUP;
switch (trigMode)
{
case 0:
break;
case 1:
connectionEvent_ |= EPOLLET;
break;
case 2:
listenEvent_ |= EPOLLET;
break;
case 3:
listenEvent_ |= EPOLLET;
connectionEvent_ |= EPOLLET;
break;
default:
listenEvent_ |= EPOLLET;
connectionEvent_ |= EPOLLET;
break;
}
HTTPconnection::isET = (connectionEvent_ & EPOLLET);
}
void WebServer::Start()
{
int timeMS=-1;//epoll wait timeout==-1就是无事件一直阻塞
if(!isClose_)
{
std::cout<<"============================";
std::cout<<"Server Start!";
std::cout<<"============================";
std::cout<<std::endl;
}
while(!isClose_)
{
if(timeoutMS_>0)
{
timeMS=timer_->getNextHandle();
}
int eventCnt=epoller_->wait(timeMS);
for(int i=0;i<eventCnt;++i)
{
int fd=epoller_->getEventFd(i);
uint32_t events=epoller_->getEvents(i);
if(fd==listenFd_)
{
handleListen_();
//std::cout<<fd<<" is listening!"<<std::endl;
}
else if(events & (EPOLLRDHUP | EPOLLHUP | EPOLLERR)) {
assert(users_.count(fd) > 0);
closeConn_(&users_[fd]);
}
else if(events & EPOLLIN) {
assert(users_.count(fd) > 0);
handleRead_(&users_[fd]);
//std::cout<<fd<<" reading end!"<<std::endl;
}
else if(events & EPOLLOUT) {
assert(users_.count(fd) > 0);
handleWrite_(&users_[fd]);
}
else {
std::cout<<"Unexpected event"<<std::endl;
}
}
}
}
void WebServer::sendError_(int fd, const char* info)
{
assert(fd>0);
int ret=send(fd,info,strlen(info),0);
if(ret<0)
{
//std::cout<<"send error to client"<<fd<<" error!"<<std::endl;
}
close(fd);
}
void WebServer::closeConn_(HTTPconnection* client)
{
assert(client);
//std::cout<<"client"<<client->getFd()<<" quit!"<<std::endl;
epoller_->delFd(client->getFd());
client->closeHTTPConn();
}
void WebServer::addClientConnection(int fd, sockaddr_in addr)
{
assert(fd>0);
users_[fd].initHTTPConn(fd,addr);
if(timeoutMS_>0)
{
timer_->addTimer(fd,timeoutMS_,std::bind(&WebServer::closeConn_,this,&users_[fd]));
}
epoller_->addFd(fd,EPOLLIN | connectionEvent_);
setFdNonblock(fd);
}
void WebServer::handleListen_() {
struct sockaddr_in addr;
socklen_t len = sizeof(addr);
do {
int fd = accept(listenFd_, (struct sockaddr *)&addr, &len);
if(fd <= 0) { return;}
else if(HTTPconnection::userCount >= MAX_FD) {
sendError_(fd, "Server busy!");
//std::cout<<"Clients is full!"<<std::endl;
return;
}
addClientConnection(fd, addr);
} while(listenEvent_ & EPOLLET);
}
void WebServer::handleRead_(HTTPconnection* client) {
assert(client);
extentTime_(client);
threadpool_->submit(std::bind(&WebServer::onRead_, this, client));
}
void WebServer::handleWrite_(HTTPconnection* client)
{
assert(client);
extentTime_(client);
threadpool_->submit(std::bind(&WebServer::onWrite_, this, client));
}
void WebServer::extentTime_(HTTPconnection* client)
{
assert(client);
if(timeoutMS_>0)
{
timer_->update(client->getFd(),timeoutMS_);
}
}
void WebServer::onRead_(HTTPconnection* client)
{
assert(client);
int ret = -1;
int readErrno = 0;
ret = client->readBuffer(&readErrno);
//std::cout<<ret<<std::endl;
if(ret <= 0 && readErrno != EAGAIN) {
//std::cout<<"do not read data!"<<std::endl;
closeConn_(client);
return;
}
onProcess_(client);
}
void WebServer::onProcess_(HTTPconnection* client)
{
if(client->handleHTTPConn()) {
epoller_->modFd(client->getFd(), connectionEvent_ | EPOLLOUT);
}
else {
epoller_->modFd(client->getFd(), connectionEvent_ | EPOLLIN);
}
}
void WebServer::onWrite_(HTTPconnection* client) {
assert(client);
int ret = -1;
int writeErrno = 0;
ret = client->writeBuffer(&writeErrno);
if(client->writeBytes() == 0) {
/* 传输完成 */
if(client->isKeepAlive()) {
onProcess_(client);
return;
}
}
else if(ret < 0) {
if(writeErrno == EAGAIN) {
/* 继续传输 */
epoller_->modFd(client->getFd(), connectionEvent_ | EPOLLOUT);
return;
}
}
closeConn_(client);
}
bool WebServer::initSocket_() {
int ret;
struct sockaddr_in addr;
if(port_ > 65535 || port_ < 1024) {
//std::cout<<"Port number error!"<<std::endl;
return false;
}
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port_);
struct linger optLinger = { 0 };
if(openLinger_) {
/* 优雅关闭: 直到所剩数据发送完毕或超时 */
optLinger.l_onoff = 1;
optLinger.l_linger = 1;
}
listenFd_ = socket(AF_INET, SOCK_STREAM, 0);
if(listenFd_ < 0) {
//std::cout<<"Create socket error!"<<std::endl;
return false;
}
ret = setsockopt(listenFd_, SOL_SOCKET, SO_LINGER, &optLinger, sizeof(optLinger));
if(ret < 0) {
close(listenFd_);
//std::cout<<"Init linger error!"<<std::endl;
return false;
}
int optval = 1;
/* 端口复用 */
/* 只有最后一个套接字会正常接收数据。 */
ret = setsockopt(listenFd_, SOL_SOCKET, SO_REUSEADDR, (const void*)&optval, sizeof(int));
if(ret == -1) {
//std::cout<<"set socket setsockopt error !"<<std::endl;
close(listenFd_);
return false;
}
ret = bind(listenFd_, (struct sockaddr *)&addr, sizeof(addr));
if(ret < 0) {
//std::cout<<"Bind Port"<<port_<<" error!"<<std::endl;
close(listenFd_);
return false;
}
ret = listen(listenFd_, 6);
if(ret < 0) {
//printf("Listen port:%d error!\n", port_);
close(listenFd_);
return false;
}
ret = epoller_->addFd(listenFd_, listenEvent_ | EPOLLIN);
if(ret == 0) {
//printf("Add listen error!\n");
close(listenFd_);
return false;
}
setFdNonblock(listenFd_);
//printf("Server port:%d\n", port_);
return true;
}
int WebServer::setFdNonblock(int fd) {
assert(fd > 0);
return fcntl(fd, F_SETFL, fcntl(fd, F_GETFD, 0) | O_NONBLOCK);
}