-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.cpp
141 lines (123 loc) · 3.2 KB
/
main.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
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <iostream>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include "FdEvents.h"
#include "Utils.h"
using namespace std;
using namespace zl;
using namespace zl::net;
// 参考lighttpd fdevent
void print_events_str(const FdEvent *fe)
{
int revents = fe->revents();
if (revents & FDEVENT_IN)
printf("FDEVENT_IN | ");
if (revents & FDEVENT_PRI)
printf("FDEVENT_PRI | ");
if (revents & FDEVENT_OUT)
printf("FDEVENT_OUT | ");
if (revents & FDEVENT_HUP)
printf("FDEVENT_HUP | ");
if (revents & FDEVENT_ERR)
printf("FDEVENT_ERR | ");
printf("\n");
}
int socket_read(FdEvents *poller, FdEvent *fe)
{
char buf[1024] = { 0 };
int fd = fe->fd();
print_events_str(fe);
// fix : loop read ( while() )
ssize_t size = zl::net::read(fd, buf, sizeof(buf));
if (size == 0) // the peer already close this connection
{
fe->disableAll(); // must disable all
poller->delFdEvent(fe);
zl::net::closeSocket(fd);
}
else
{
printf("server recv[%d] msg[%s]\n", fd, buf);
zl::net::write(fd, buf, size);
}
return 0;
}
int socket_write(FdEvents *poller, FdEvent *fe)
{
return 0;
}
int socket_accept(FdEvents *poller, FdEvent *fe)
{
int srvfd = fe->fd();
int max_accept = 0;
while (max_accept < 100)
{
struct sockaddr_in addr;
int clientfd = zl::net::accept(srvfd, &addr);
if (clientfd > 0)
{
printf("get one client [%d]\n", clientfd);
zl::net::setNonBlocking(clientfd);
poller->addFdEvent(clientfd, socket_read);
const char *welcome = "hello world, welcome to connecting server\n";
zl::net::write(clientfd, welcome, strlen(welcome));
}
else
{
switch (errno)
{
case EAGAIN:
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
case EINTR:
break;
case EMFILE: // out of fds
break;
default:
perror("socket_accept : ");
break;
}
break;
}
}
return 0;
}
void test_server()
{
int srvsock = createSocketAndListen("127.0.0.1", 8888, 1023);
assert(srvsock > 0);
FdEvents *poller = createFdEvents();
assert(poller);
cout << poller->getName() << "\n";
zl::net::setNonBlocking(srvsock);
poller->addFdEvent(srvsock, socket_accept);
std::vector<FdEvent *> fdevents;
while (1)
{
fdevents.clear();
int nfds = poller->poll(fdevents, 10000); // 10000 ms
if (nfds == 0)
{
continue;
}
else if (nfds == -1)
{
break;
}
assert(nfds == static_cast<int>(fdevents.size()));
for (int i = 0; i < nfds; i++)
{
FdEvent *fde = fdevents[i];
fde->callback_(poller, fde);
}
}
delete poller;
}
int main()
{
test_server();
return 0;
}