-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAcceptor.cpp
58 lines (53 loc) · 1.77 KB
/
Acceptor.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
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include "Acceptor.h"
#include "Logger.h"
#include "InetAddress.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);
//Tcpserver start()->acceptor listen() connfd->channel->subloop
// baseLoop->acceptChannel_(listenfd)
acceptChannel_.setReadCallback(std::bind(&Acceptor::handleRead, this));
}
Acceptor::~Acceptor(){
acceptChannel_.disableAll();
acceptChannel_.remove();
}
void Acceptor::listen(){
listenning_ = true;
acceptSocket_.listen();
acceptChannel_.enableReading();
}
//接受新连接,负载均衡分发给subloop
void Acceptor::handleRead(){
InetAddress peerAddr;
int connfd = acceptSocket_.accept(&peerAddr);
if( connfd >= 0 ){
if(newConnectionCallback_){
newConnectionCallback_(connfd, peerAddr); //轮询找到subloop,唤醒并分发给其当前channel
}else{
::close(connfd);
}
}else{
LOG_ERROR("%s:%s:%d accept err:%d \n", __FILE__, __FUNCTION__, __LINE__, errno);
if(errno == EMFILE){ //没有资源分配fd
LOG_ERROR("%s:%s:%d sockfd reached err:%d \n", __FILE__, __FUNCTION__, __LINE__, errno);
}
}
}