epoll — The server — monitor — fd ---- Can be read ---- epoll return ---- read — Small to capital — write ---- epoll Keep listening .
epoll Reactor model :
establish efd(epoll_create) ---- increase fd(epoll_ctl) ---- epoll_wait return ----fd Can be read ---- read ---- fd Pick from the tree ---- Set listening fd Write events , operation senddata ---- Small to capital ( Or a direct shot back ) ---- wait for epoll_wait return ---- Write back to the client ----efd Pick from the tree ---- Set listening cfd Read events , operation recvdata----epoll Keep listening
1 /*
2 *epoll Based on non blocking I/O Event driven
3 */
#include <stdio.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define MAX_EVENTS 1024 // The upper limit the red black tree can listen to
#define BUFLEN 4096
#define SERV_PORT 8080
void recvdata(int fd, int events, void *arg);
void senddata(int fd, int events, void *arg);
/* Describes information about ready file descriptors */
struct myevent_s {
int fd; // The file descriptor to listen to
int events; // The corresponding listening event
void *arg; // The generic parameter
void(*call_back)(int fd, int events, void *arg); // Callback function
int status; // Is it listening :1-> On the red and black trees ( monitor ), 0-> be not in ( No monitoring )
char buf[BUFLEN];
int len;
long last_active; // Record every time you add a red black tree g_efd Time value of ( If you don't send data for a long time , Then kick it out ),eventset and add This time will be reset
};
int g_efd; // Global variables , preservation epoll_create File descriptor returned
struct myevent_s g_events[MAX_EVENTS + 1]; // Custom structure type array . +1-->listen fd
/* The structure myevent_s Member variables initialization */
// Callback function call_back Parameters of arg It's the structure myevent_s In itself
void eventset(struct myevent_s *ev, int fd, void(*call_back)(int, int, void *), void *arg)
{
ev->fd = fd;
ev->call_back = call_back;
ev->events = 0;
ev->arg = arg;
ev->status = 0;
memset(ev->buf, 0, sizeof(ev->buf));
ev->len = 0;
ev->last_active = time(NULL); // call eventset Time of function ( Once called, it changes ), If it hasn't changed for a long time ( Confiscating data ), It will be deleted
return;
}
/* towards epoll Monitoring the red and black tree Add one File descriptor */
void eventadd(int efd, int events, struct myevent_s *ev)
{
struct epoll_event epv = {
0, {
0 } };
int op;
epv.data.ptr = ev;
epv.events = ev->events = events; //EPOLLIN or EPOLLOUT
if (ev->status == 1) // Already in the red and black tree g_efd in
{
op = EPOLL_CTL_MOD; // Modify its properties
}
else{
// Not in the red and black trees g_efd in
op = EPOLL_CTL_ADD; // Add it to the red black tree g_efd, And will status Set up 1
ev->status = 1;
}
if (epoll_ctl(efd, op, ev->fd, &epv) < 0) // Actual addition / modify
printf("event add failed [fd=%d], events[%d]\n", ev->fd, events);
else
printf("event add OK [fd=%d], op=%d, events[%0X]\n", ev->fd, op, events);
return;
}
/* from epoll Monitoring Delete one from the red and black tree File descriptor */
void eventdel(int efd, struct myevent_s *ev)
{
struct epoll_event epv = {
0, {
0 } };
if (ev->status != 1) // Not on the black and red tree
return;
//epv.data.ptr = ev;
epv.data.ptr = NULL;
ev->status = 0; // modify state
epoll_ctl(efd, EPOLL_CTL_DEL, ev->fd, &epv); // From the red and black trees efd Admiral ev->fd Enucleation
return;
}
/* When a file descriptor is ready , epoll return , Call this function Link with client */
void acceptconn(int lfd, int events, void *arg)
{
struct sockaddr_in cin;
socklen_t len = sizeof(cin);
int cfd, i;
if ((cfd = accept(lfd, (struct sockaddr *)&cin, &len)) == -1) {
if (errno != EAGAIN && errno != EINTR) {
/* No error handling for the time being */
}
printf("%s: accept, %s\n", __func__, strerror(errno));//__func__ The current corresponding function name
return;
}
do {
for (i = 0; i < MAX_EVENTS; i++) // From global array g_events Find a free element in
if (g_events[i].status == 0) // Be similar to select The median value is -1 The elements of
break; // Jump out of for
if (i == MAX_EVENTS) {
printf("%s: max connect limit[%d]\n", __func__, MAX_EVENTS);
break; // Jump out of do while(0) Do not execute subsequent code
}
int flag = 0;
if ((flag = fcntl(cfd, F_SETFL, O_NONBLOCK)) < 0) {
// take cfd Also set to non blocking
printf("%s: fcntl nonblocking failed, %s\n", __func__, strerror(errno));
break;
}
/* to cfd Set up a myevent_s Structure , Callback function Set to recvdata */
eventset(&g_events[i], cfd, recvdata, &g_events[i]); // The callback function has changed
eventadd(g_efd, EPOLLIN, &g_events[i]); // take cfd Add to the red black tree g_efd in , Listen to read events
} while (0);
printf("new connect [%s:%d][time:%ld], pos[%d]\n",
inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), g_events[i].last_active, i);
return;
}
void recvdata(int fd, int events, void *arg)
{
struct myevent_s *ev = (struct myevent_s *)arg;
int len;
//recv Specifically for reading sockets ,recv The last pass 0 Just like read The same
len = recv(fd, ev->buf, sizeof(ev->buf), 0); // Read file descriptor , Data stored in myevent_s member buf in
eventdel(g_efd, ev); // Remove the node from the red and black tree
if (len > 0) {
ev->len = len;
ev->buf[len] = '\0'; // Add string end tag manually
printf("C[%d]:%s\n", fd, ev->buf);
eventset(ev, fd, senddata, ev); // Set the fd The corresponding callback function is senddata
eventadd(g_efd, EPOLLOUT, ev); // take fd Join the red and black trees g_efd in , Listen to its write events
}
else if (len == 0) {
close(ev->fd);
/* ev-g_events The offset element position is obtained by subtracting the address */
printf("[fd=%d] pos[%ld], closed\n", fd, ev - g_events);
}
else {
close(ev->fd);
printf("recv[fd=%d] error[%d]:%s\n", fd, errno, strerror(errno));
}
return;
}
void senddata(int fd, int events, void *arg)
{
struct myevent_s *ev = (struct myevent_s *)arg;
int len;
len = send(fd, ev->buf, ev->len, 0); // Directly transfer data Write back to the client . Not processed
/*
175 printf("fd=%d\tev->buf=%s\ttev->len=%d\n", fd, ev->buf, ev->len);
176 printf("send len = %d\n", len);
177 */
eventdel(g_efd, ev); // From the red and black trees g_efd Remove
if (len > 0) {
printf("send[fd=%d], [%d]%s\n", fd, len, ev->buf);
eventset(ev, fd, recvdata, ev); // Will be fd Of The callback function is changed to recvdata
eventadd(g_efd, EPOLLIN, ev); // From the new add to the red and black tree , Set to listen for read events
}
else {
close(ev->fd); // Close links
printf("send[fd=%d] error %s\n", fd, strerror(errno));
}
return;
}
/* establish socket, initialization lfd */
void initlistensocket(int efd, short port)
{
struct sockaddr_in sin;
int lfd = socket(AF_INET, SOCK_STREAM, 0);
fcntl(lfd, F_SETFL, O_NONBLOCK); // take socket Set to non blocking
memset(&sin, 0, sizeof(sin)); //bzero(&sin, sizeof(sin))
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(port);
bind(lfd, (struct sockaddr *)&sin, sizeof(sin));
listen(lfd, 20);
/* The structure myevent_s Member variables initialization */ // The parameters passed by the callback function are the structure itself
/* void eventset(struct myevent_s *ev, int fd, void (*call_back)(int, int, void *), void *arg); */
eventset(&g_events[MAX_EVENTS], lfd, acceptconn, &g_events[MAX_EVENTS]);// Direct will listenfd Put it at the end of the array
/* towards epoll Monitoring the red and black tree Add one File descriptor */
/* void eventadd(int efd, int events, struct myevent_s *ev) */
eventadd(efd, EPOLLIN, &g_events[MAX_EVENTS]);
return;
}
int main(int argc, char *argv[])
{
unsigned short port = SERV_PORT;
if (argc == 2)
port = atoi(argv[1]); // Use user specified port . If not specified , Use default port
g_efd = epoll_create(MAX_EVENTS + 1); // Create a red black tree , Back to the big picture g_efd
if (g_efd <= 0)
printf("create efd in %s err %s\n", __func__, strerror(errno));
initlistensocket(g_efd, port); // Initialize listening socket
struct epoll_event events[MAX_EVENTS + 1]; // Save an array of file descriptors that have satisfied the ready event
printf("server running:port[%d]\n", port);
int checkpos = 0, i;
while (1) {
/* Timeout verification , Every test 100 A link , Don't test listenfd When the client 60 No communication with the server in seconds , Then close the client link */
long now = time(NULL); // current time
for (i = 0; i < 100; i++, checkpos++)
{
// Primary cycle detection 100 individual . Use checkpos Control test object
if (checkpos == MAX_EVENTS)
checkpos = 0;
if (g_events[checkpos].status != 1) // Not in the red and black trees g_efd On
continue;
long duration = now - g_events[checkpos].last_active; // The world where the client is not active
if (duration >= 60)
{
close(g_events[checkpos].fd); // Close the link with the client
printf("[fd=%d] timeout\n", g_events[checkpos].fd);
eventdel(g_efd, &g_events[checkpos]); // Put the client From the red and black trees g_efd remove
}
}//for
/* Monitor the red black tree g_efd, Add the event descriptor to the file events Array , 1 Second no event satisfies , return 0*/
int nfd = epoll_wait(g_efd, events, MAX_EVENTS + 1, 1000);
if (nfd < 0)
{
printf("epoll_wait error, exit\n");
break;
}
for (i = 0; i < nfd; i++)
{
/* Use custom structs myevent_s Type a pointer , receive Consortium data Of void *ptr member */
struct myevent_s *ev = (struct myevent_s *)events[i].data.ptr;
if ((events[i].events & EPOLLIN) && (ev->events & EPOLLIN))
{
// Read ready event
ev->call_back(ev->fd, events[i].events, ev->arg);
}
if ((events[i].events & EPOLLOUT) && (ev->events & EPOLLOUT))
{
// Write ready event
ev->call_back(ev->fd, events[i].events, ev->arg);
}
}//for
}//while(1)
/* Release all resources before exiting */
return 0;
}