forked from linyacool/WebServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
executable file
·77 lines (72 loc) · 2.54 KB
/
Server.cpp
File metadata and controls
executable file
·77 lines (72 loc) · 2.54 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
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#include "Server.h"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <functional>
#include "Util.h"
#include "base/Logging.h"
Server::Server(EventLoop *loop, int threadNum, int port)
: loop_(loop),
threadNum_(threadNum),
eventLoopThreadPool_(new EventLoopThreadPool(loop_, threadNum)),
started_(false),
acceptChannel_(new Channel(loop_)),
port_(port),
listenFd_(socket_bind_listen(port_)) {
acceptChannel_->setFd(listenFd_);
handle_for_sigpipe();
if (setSocketNonBlocking(listenFd_) < 0) {
perror("set socket non block failed");
abort();
}
}
void Server::start() {
eventLoopThreadPool_->start();
// acceptChannel_->setEvents(EPOLLIN | EPOLLET | EPOLLONESHOT);
acceptChannel_->setEvents(EPOLLIN | EPOLLET);
acceptChannel_->setReadHandler(bind(&Server::handNewConn, this));
acceptChannel_->setConnHandler(bind(&Server::handThisConn, this));
loop_->addToPoller(acceptChannel_, 0);
started_ = true;
}
void Server::handNewConn() {
struct sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(struct sockaddr_in));
socklen_t client_addr_len = sizeof(client_addr);
int accept_fd = 0;
while ((accept_fd = accept(listenFd_, (struct sockaddr *)&client_addr,
&client_addr_len)) > 0) {
EventLoop *loop = eventLoopThreadPool_->getNextLoop();
LOG << "New connection from " << inet_ntoa(client_addr.sin_addr) << ":"
<< ntohs(client_addr.sin_port);
// cout << "new connection" << endl;
// cout << inet_ntoa(client_addr.sin_addr) << endl;
// cout << ntohs(client_addr.sin_port) << endl;
/*
// TCP的保活机制默认是关闭的
int optval = 0;
socklen_t len_optval = 4;
getsockopt(accept_fd, SOL_SOCKET, SO_KEEPALIVE, &optval, &len_optval);
cout << "optval ==" << optval << endl;
*/
// 限制服务器的最大并发连接数
if (accept_fd >= MAXFDS) {
close(accept_fd);
continue;
}
// 设为非阻塞模式
if (setSocketNonBlocking(accept_fd) < 0) {
LOG << "Set non block failed!";
// perror("Set non block failed!");
return;
}
setSocketNodelay(accept_fd);
// setSocketNoLinger(accept_fd);
shared_ptr<HttpData> req_info(new HttpData(loop, accept_fd));
req_info->getChannel()->setHolder(req_info);
loop->queueInLoop(std::bind(&HttpData::newEvent, req_info));
}
acceptChannel_->setEvents(EPOLLIN | EPOLLET);
}