-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAcceptor.cpp
More file actions
128 lines (86 loc) · 2.2 KB
/
Acceptor.cpp
File metadata and controls
128 lines (86 loc) · 2.2 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
#include "Acceptor.h"
#include "Connctx.h"
using namespace std;
Acceptor::Acceptor(int port, NewConnHandler newconn_handler)
:port_(port),
newconn_handler_(newconn_handler),
listen_fd_(-1)
{
}
Acceptor::~Acceptor()
{
}
int Acceptor::listen()
{
int s, on = 1;
struct sockaddr_in sa;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
log_error("creating socket: %s", strerror(errno));
return -1;
}
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
{
log_error("setsockopt SO_REUSEADDR: %s", strerror(errno));
return -1;
}
memset(&sa,0,sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(this->port_);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s,(struct sockaddr*)&sa,sizeof(sa)) == -1) {
log_error("bind: %s", strerror(errno));
close(s);
return -1;
}
if (::listen(s, eBackLog) == -1) {
log_error("listen: %s", strerror(errno));
close(s);
return -1;
}
this->listen_fd_ = s;
return s;
}
int Acceptor::acceptfd(int listen_fd, struct sockaddr *sa, socklen_t* len)
{
int fd = -1;
bool flag = true;
while(flag) {
fd = accept(listen_fd,sa,len);
if (fd == -1) {
if (errno == EINTR)
{
flag = false;
continue;
}
else {
log_error("accept: %s", strerror(errno));
return -1;
}
}
break;
}
return fd;
}
Connctx* Acceptor::acceptfd()
{
struct sockaddr_in sa;
socklen_t salen = sizeof(sa);
int newconn_fd = -1;
if((newconn_fd = this->acceptfd(this->listen_fd_,(struct sockaddr*)&sa,&salen)) < 0)
{
return NULL;
}
//conn will be released when the work is done or some error's happen.
Connctx* newctx = new Connctx(newconn_fd);
return newctx;
}
void Acceptor::accept_handler(EventLoop *el, void *acceptor)
{
Connctx* ctx = ((Acceptor*)acceptor)->acceptfd();
if(ctx == NULL)
{
return;
}
((Acceptor*)acceptor)->newconn_handler_(el,ctx);
}