Repository navigation
Expand file tree
/
Copy pathwebserver.h
More file actions
321 lines (277 loc) · 8.99 KB
/
Copy pathwebserver.h
File metadata and controls
321 lines (277 loc) · 8.99 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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//
// Created by Hanhong Wong on 2026/4/20.
//
#ifndef MYWEBSERVER_WEBSERVER_H
#define MYWEBSERVER_WEBSERVER_H
#include <cassert>
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <vector>
#include <sys/epoll.h>
#include "http_conn/HttpConnect.h"
#include "routes/routes.h"
#include "log/async_log.h"
#include "log/log.h"
#include "threadpool/threadpool.h"
#include "timer/timer_policy.h"
#include "timer/timer_lst.h"
#include "timer/timer_wheel.h"
#include "util/types.h"
//threads number for thread pool
constexpr int THREAD_NUM = 8;
//max connect number
constexpr int MAX_FD = 1024;
//time spand for one tick
constexpr int TIME_SLOT = 5;
//epoll table size
constexpr int MAX_EVENT_NUM = 10000;
class WebServer {
private:
//http_conn
HttpConnect* m_user_ = {};
// 路由表:所有连接共享,负责将 URL 分发给对应的 handler
Router m_router_ = {};
//threadpool
Threadpool<HttpConnect>* m_thread_pool_ = {};
//epoll
int m_server_fd_ = {-1};
int m_epoll_fd_ = {-1};
int m_actor_model_ = {}; //Reactor : 0, Proactor : 1;
//timer
int m_pipe_fd_[2] = {};
int m_timer_model_ = {};
Util m_util_ = {};
client_data* m_user_timer_ = {};
//log
int m_close_log_ = {};
int m_log_model_ = {};
//database
MySQLClient m_mysql_client_ =
{"localhost", "root", "", "webserver"};
//初始化新的http连接,初始化该连接对应的定时器
void createConn(int connfd) {
m_user_[connfd].init(connfd);
m_user_timer_[connfd].m_sock_fd_ = connfd;
auto timer = m_util_.m_timer_->create_timer();
timer->cb_func = cb_func;
timer->user_data_ = &m_user_timer_[connfd];
timer->adjust_expire(TIME_SLOT);
m_user_timer_[connfd].m_timer_ = timer;
m_util_.m_timer_->add_timer(timer);
}
public:
WebServer() {
m_user_ = new HttpConnect[MAX_FD];
m_user_timer_ = new client_data[MAX_FD];
}
~WebServer() {
delete m_thread_pool_;
delete[] m_user_;
delete[] m_user_timer_;
if (m_epoll_fd_ >= 0)
close(m_epoll_fd_);
if (m_server_fd_ >= 0)
close(m_server_fd_);
}
void init(int m_actor_model, int m_log_model, int m_close_log, int m_timer_model) {
m_actor_model_ = m_actor_model;
m_log_model_ = m_log_model;
m_close_log_ = m_close_log;
m_timer_model_ = m_timer_model;
}
void createThreadPool() {
m_thread_pool_ = new Threadpool<HttpConnect>(THREAD_NUM, MAX_FD, m_actor_model_);
}
void createLog() const {
if (m_log_model_ == 0) {
Log::getInstance()->init("./ServerLog", m_close_log_, 2048, 5000000, 800);
}
if (m_log_model_ == 1) {
Async_Log::getInstance()->init("./ServerLog", m_close_log_);
}
}
void registerRoutes() {
// 所有路由定义在 http_conn/routes.h 中,按 RouteHandler 子类组织
registerAllRoutes(m_router_, m_mysql_client_);
}
void start() {
// ---- 初始化路由表 ----
// 在绑定端口前注册所有路由,确保首次请求时路由已就绪
registerRoutes();
// 将路由表指针注入 HttpConnect(静态成员,所有连接实例共享)
HttpConnect::m_router_ = &m_router_;
//网络编程基础步骤
m_server_fd_ = socket(AF_INET, SOCK_STREAM, 0);
assert(m_server_fd_ >= 0);
// 允许端口快速复用,避免压测重启时 "Address already in use"
int opt = 1;
setsockopt(m_server_fd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = INADDR_ANY;
memset(addr.sin_zero, '\0', sizeof addr.sin_zero);
int ret = bind(m_server_fd_, (sockaddr*)&addr, sizeof(addr));
assert(ret >= 0);
ret = listen(m_server_fd_, 65535);
assert(ret >= 0);
//
m_util_.setnonblocking(m_server_fd_);
//创建内核epoll事件表
m_epoll_fd_ = epoll_create1(0);
assert(m_epoll_fd_ >= 0);
m_util_.addfd(m_epoll_fd_, m_server_fd_, false);
HttpConnect::m_epollfd_ = m_epoll_fd_;
//定时器相关
ret = socketpair(AF_UNIX, SOCK_STREAM, 0, m_pipe_fd_);
assert(ret >= 0);
Util::u_epoll_fd_ = m_epoll_fd_;
Util::u_pipe_fd_ = m_pipe_fd_;
m_util_.init(TIME_SLOT);
//设定定时器模式
if (m_timer_model_ == 0) {
m_util_.init_timer(std::make_unique<sort_timer_lst>());
}
if (m_timer_model_ == 1) {
m_util_.init_timer(std::make_unique<timer_wheel>());
}
m_util_.setnonblocking(m_pipe_fd_[1]);
m_util_.addfd(m_epoll_fd_, m_pipe_fd_[0], false);
m_util_.addsig(SIGPIPE, SIG_IGN, false);
m_util_.addsig(SIGALRM, Util::sig_handler, false);
m_util_.addsig(SIGTERM, Util::sig_handler, false);
alarm(TIME_SLOT);
Async_Log::LOG_INFO("Web server started on port %d", 8888);
}
void adjustTimer(int fd) {
auto timer = m_user_timer_[fd].m_timer_;
if (timer) {
timer->adjust_expire(TIME_SLOT);
m_util_.m_timer_->adjust_timer(timer);
LOG_INFO("adjust fd %d's timer", fd);
}
}
void dealWithTimer(int fd) {
auto timer = m_user_timer_[fd].m_timer_;
if (timer) {
timer->cb_func(timer->user_data_);
m_util_.m_timer_->del_timer(timer);
LOG_INFO("delete fd %d's timer", fd);
}
}
bool dealwithclient() {
while (true) {
int client_fd = accept(m_server_fd_, nullptr, nullptr);
if (client_fd < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
break;
}
if (errno == EINTR) {
continue;
}
perror("accept");
break;
}
if (client_fd >= MAX_FD) {
return false;
}
createConn(client_fd);
}
return true;
}
void dealwithread(int fd) {
auto conn = m_user_ + fd;
if (m_actor_model_ == 0) {
adjustTimer(fd);
m_thread_pool_->append_s(conn, 0);
}
else {
if (conn->read()) {
m_thread_pool_->append(conn);
adjustTimer(fd);
}
else {
dealWithTimer(fd);
}
}
}
void dealwithwrite(int fd) {
auto conn = m_user_ + fd;
if (m_actor_model_ == 0) {
adjustTimer(fd);
m_thread_pool_->append_s(conn, 1);
}
else {
if (conn->write()) {
adjustTimer(fd);
}
else {
dealWithTimer(fd);
}
}
}
bool dealwithsignal(bool& timeout, bool& stop_server) {
char signals[1024];
int ret = recv(m_pipe_fd_[0], &signals, sizeof(signals), 0);
if (ret < 1) {
LOG_ERROR("%s", "dealwithsignal error.");
return false;
}
for (int _ = 0; _ < ret; ++_) {
switch (signals[_]) {
case SIGALRM:
timeout = true;
break;
case SIGTERM:
stop_server = true;
break;
default:
break;
}
}
return true;
}
void loop() {
std::vector<epoll_event> events(MAX_EVENT_NUM);
bool timeout = false;
bool stop_server = false;
while (!stop_server) {
int n = epoll_wait(m_epoll_fd_, events.data(), MAX_EVENT_NUM, -1);
if (n < 0 && errno != EINTR) {
LOG_ERROR("%s", "epoll_wait error");
break;
}
for (int i = 0; i < n; ++i) {
int fd = events[i].data.fd;
if (fd == m_server_fd_) { // 新连接
if (!dealwithclient()) {
continue;
}
}
else if (events[i].events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
dealWithTimer(fd);
//错误,关闭连接;
}
else if ((fd == m_pipe_fd_[0]) && (events[i].events & EPOLLIN)) {
dealwithsignal(timeout, stop_server);
//sig信号处理
}
else if (events[i].events & EPOLLIN) {
dealwithread(fd);
}
else if (events[i].events & EPOLLOUT) {
dealwithwrite(fd);
}
}
if (timeout) {
m_util_.time_handler();
LOG_INFO("%s", "tick.");
timeout = false;
}
}
}
};
#endif //MYWEBSERVER_WEBSERVER_H