-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.cpp
62 lines (54 loc) · 1.88 KB
/
Server.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
#include "Server.h"
#include "Http_conn.h"
#include "EventLoop.h"
#include "ThreadpoolEventLoop.h"
#include "Logging.h"
#include "MemoryPool.h"
Server::Server(const char* port, int threadnum)
: loop(newElement<EventLoop>(), deleteElement<EventLoop>),
serverchannel(newElement<Channel>(loop), deleteElement<Channel>),
iothreadpool(newElement<ThreadpoolEventLoop>(threadnum),deleteElement<ThreadpoolEventLoop>)
{
listenfd = tcp_listen(NULL, port, NULL);
setnonblocking(listenfd);
serverchannel->setFd(listenfd);
}
Server::~Server(){
Close(listenfd);
}
void Server::start(){
iothreadpool->start();
serverchannel->setRevents(EPOLLIN | EPOLLET);
serverchannel->setReadhandler(bind(&Server::handleconn, this));
loop->addPoller(serverchannel);
LOG << "Start";
loop->loop();
}
void Server::handleconn(){
struct sockaddr_storage cliaddr;
socklen_t clilen = sizeof(cliaddr);
int connfd;
while( (connfd = Accept(listenfd, (SA*)& cliaddr, &clilen) ) >= 0){
LOG << "Accept Fd = " << connfd;
setnonblocking(connfd);
SP_EventLoop nextloop = iothreadpool->getNextloop();
SP_Channel connchannel(newElement<Channel>(nextloop),
deleteElement<Channel>);
connchannel->setFd(connfd);
WP_Channel wpchannel = connchannel;
connchannel->setClosehandler(bind(&Server::handleclose, this, wpchannel));
connchannel->setRevents(EPOLLIN | EPOLLET);
SP_Http_conn connhttp(newElement<Http_conn>(connchannel),deleteElement<Http_conn>);
Httpmap[connfd] = move(connhttp);
nextloop->queueInLoop(bind(&EventLoop::addPoller, nextloop,
move(connchannel)));
}
}
void Server::handleclose(WP_Channel channel){
SP_Channel spchannel = channel.lock();
loop->queueInLoop(bind(&Server::deletemap, this, spchannel));
spchannel->getLoop().lock()->removePoller(spchannel);
}
void Server::deletemap(SP_Channel channel){
Httpmap.erase(channel->getFd());
}