-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEpollTest2.cpp
135 lines (109 loc) · 2.68 KB
/
EpollTest2.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
/*
* =====================================================================================
*
* Filename: EpollTest.cpp
*
* Description:
*
* Version: 1.0
* Created: 08/31/2017 02:46:29 PM
* Last Modified: 08/31/2017 02:46:29 PM
* Revision: none
* Compiler: gcc
*
* Author: zt (),
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <map>
#include <memory>
#include <iostream>
#include "Network.cpp"
#define MAX_CNT (2048)
typedef int ( *Fun ) ( int fd );
struct my_epoll_t
{
my_epoll_t ( int _fd, Fun _pFun )
{
fd = _fd;
pFun = _pFun;
}
~my_epoll_t()
{
shutdown ( fd, SHUT_RDWR );
close ( fd );
}
int fd;
Fun pFun;
};
int F1 ( int fd )
{
int ret = 0;
char buffer[2048];
ret = read ( fd, buffer, 2048 );
//ret = Network::Recvn ( fd, buffer, 2048 );
if ( ret > 0 )
printf ( "fd=%d recv=%d %s\n", fd, ret, buffer );
return ret;
}
int F2 ( int fd )
{
char buffer[2048];
return Network::Sendn ( fd, buffer, 2048 );
}
int main ( int argc, char* argv[] )
{
int listensock = Network::MakeTCPServer ( 12345 );
int ret = -1;
epoll_event ev;
epoll_event events[MAX_CNT];
int epollfd = epoll_create1 ( 0 );
ev.data.fd = listensock;
ev.events = EPOLLIN;
ret = epoll_ctl ( epollfd, EPOLL_CTL_ADD, listensock, &ev );
printf ( "epoll_ctl, add listensock ret %d\n", ret );
int nfd = 0;
while ( 1 )
{
nfd = epoll_wait ( epollfd, events, MAX_CNT, 1000 );
for ( int i = 0; i < nfd; ++i )
{
if ( events[i].data.fd == listensock )
{
sockaddr saddr;
int sk = Network::MakeAccept ( listensock, &saddr );
Network::SetNonBlock ( sk );
ev.data.ptr = new my_epoll_t ( sk, F1 );
ev.events = EPOLLIN | EPOLLET;
ret = epoll_ctl ( epollfd, EPOLL_CTL_ADD, sk, &ev );
printf ( "incomming connect %d %s ret=%d \n",
sk, inet_ntoa ( reinterpret_cast<sockaddr_in*> ( &saddr )->sin_addr ), ret );
}
else
{
my_epoll_t* p = reinterpret_cast< my_epoll_t*> ( events[i].data.ptr );
ret = p->pFun ( p->fd );
if ( ret <= 0 )
{
ev.data.fd = p->fd;
ev.events = 0;
epoll_ctl ( epollfd, EPOLL_CTL_DEL, p->fd, &ev );
delete p;
printf ( "line=%d del connect %d ret=%d\n",
__LINE__, ev.data.fd, ret );
}
else
{
//printf ( "line=%d ret=%d\n", __LINE__, ret );
}
}
}
}
close ( epollfd );
close ( listensock );
return 0;
}