-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAcceptor.cc
More file actions
56 lines (49 loc) · 1.57 KB
/
Acceptor.cc
File metadata and controls
56 lines (49 loc) · 1.57 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
#include "Acceptor.h"
#include "Logger.h"
#include "Channel.h"
#include "InetAddress.h"
#include <sys/socket.h>
#include <unistd.h>
static int createNonblocking() {
int sockfd = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if(sockfd < 0) {
LOG_FATAL("%s:%s:%d listen socket create err:%d \n", __FILE__, __FUNCTION__, __LINE__, errno);
}
return sockfd;
}
Acceptor::Acceptor(EventLoop *loop, const InetAddress &listenAddr, bool reuseport)
: loop_(loop), acceptSocket_(createNonblocking())
, acceptChannel_(loop_, acceptSocket_.fd()), listenning_(false) {
acceptSocket_.setReuseAddr(true);
acceptSocket_.setReusePort(true);
acceptSocket_.bindAddress(listenAddr);
acceptChannel_.setReadCallback(std::bind(&Acceptor::handleRead, this));
}
Acceptor::~Acceptor() {
acceptChannel_.disableAll();
acceptChannel_.remove();
}
void Acceptor::listen() {
listenning_ = true;
acceptSocket_.listen();
acceptChannel_.enableReading();
}
// 有连接事件到来
void Acceptor::handleRead(){
InetAddress peerAddr;
int connfd = acceptSocket_.accept(&peerAddr);
if(connfd >= 0) {
if(newConnectionCallback_) {
newConnectionCallback_(connfd, peerAddr);
}
else {
::close(connfd);
}
}
else {
LOG_FATAL("%s:%s:%d accept err:%d \n \n", __FILE__, __FUNCTION__, __LINE__, errno);
if(errno == EMFILE) { // too many open files
LOG_ERROR("%s:%s:%d sockfd reached limit! \n", __FILE__, __FUNCTION__, __LINE__);
}
}
}