linux网络编程之用epoll实现io复用(基于tcp)

1、epoll介绍

  epoll是在2.6内核中提出的,是之前的select和poll的增强版本。相对于select和poll来说,epoll更加灵活,没有描述符限制。epoll使用一个文件描述符管理多个描述符,将用户关系的文件描述符的事件存放到内核的一个事件表中,这样在用户空间和内核空间的copy只需一次。


2、epollAPI

epoll操作过程需要三个接口,分别如下:

#include 
int epoll_create(int size);
int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout);

(1) int epoll_create(int size);
  创建一个epoll的句柄,size用来告诉内核这个监听的数目一共有多大。这个参数不同于select()中的第一个参数,给出最大监听的fd+1的值。需要注意的是,当创建好epoll句柄后,它就是会占用一个fd值,在linux下如果查看/proc/进程id/fd/,是能够看到这个fd的,所以在使用完epoll后,必须调用close()关闭,否则可能导致fd被耗尽。

(2)int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event);
  epoll的事件注册函数,它不同与select()是在监听事件时告诉内核要监听什么类型的事件epoll的事件注册函数,而是在这里先注册要监听的事件类型。第一个参数是epoll_create()的返回值,第二个参数表示动作,用三个宏来表示:
EPOLL_CTL_ADD:注册新的fd到epfd中;
EPOLL_CTL_MOD:修改已经注册的fd的监听事件;
EPOLL_CTL_DEL:从epfd中删除一个fd;

注意这里EPOLL_CTL_ADD和EPOLL_CTL_MOD和EPOLL_CTL_DEL都是整形数据,他们的值分别是1,2, 3。读者可以自己测试。

第三个参数是需要监听的fd,第四个参数是告诉内核需要监听什么事,struct epoll_event结构如下:

struct epoll_event {
  __uint32_t events;  /* Epoll events */
  epoll_data_t data;  /* User data variable */
};

events可以是以下几个宏的集合:
EPOLLIN :表示对应的文件描述符可以读(包括对端SOCKET正常关闭);
EPOLLOUT:表示对应的文件描述符可以写;
EPOLLPRI:表示对应的文件描述符有紧急的数据可读(这里应该表示有带外数据到来);
EPOLLERR:表示对应的文件描述符发生错误;
EPOLLHUP:表示对应的文件描述符被挂断;
EPOLLET: 将EPOLL设为边缘触发(Edge Triggered)模式,这是相对于水平触发(Level Triggered)来说的。
EPOLLONESHOT:只监听一次事件,当监听完这次事件之后,如果还需要继续监听这个socket的话,需要再次把这个socket加入到EPOLL队列里

(3) int epoll_wait(int epfd, struct epoll_event * events, int maxevents, int timeout);
  等待事件的产生,类似于select()调用。参数events用来从内核得到事件的集合,maxevents告之内核这个events有多大,参数timeout是超时时间(毫秒,0会立即返回,-1将不确定,也有说法说是永久阻塞)。该函数返回需要处理的事件数目,如返回0表示已超时。


3、工作模式

  epoll对文件描述符的操作有两种模式:LT(level trigger)和ET(edge trigger)。LT模式是默认模式,LT模式与ET模式的区别如下:
  LT模式:当epoll_wait检测到描述符事件发生并将此事件通知应用程序,应用程序可以不立即处理该事件。下次调用epoll_wait时,会再次响应应用程序并通知此事件。
  ET模式:当epoll_wait检测到描述符事件发生并将此事件通知应用程序,应用程序必须立即处理该事件。如果不处理,下次调用epoll_wait时,不会再次响应应用程序并通知此事件。

  ET模式在很大程度上减少了epoll事件被重复触发的次数,因此效率要比LT模式高。epoll工作在ET模式的时候,必须使用非阻塞套接口,以避免由于一个文件句柄的阻塞读/阻塞写操作把处理多个文件描述符的任务饿死。


4、用epoll测试客户端发消息到服务端,然后服务端把收到的消息再发给客户端


   1)服务端tcp_epoll_server.c代码如下

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define IPADDRESS "127.0.0.1"
#define PORT 8888
#define MAXSIZE 1024
#define LISTENQ 5
#define FDSIZE 1000
#define EPOLLEVENTS 100

//bind socket
static int socket_bind(const char* ip, int port);
//io epoll
static void do_epoll(int listenfd);
//deal with events
static void handle_events(int epollfd, struct epoll_event *event, int num, int listenfd, char *buf);
//deal with accpet events
static void handle_accpet(int epolled, int listenfd);
//deal with read
static void do_read(int epollfd, int fd, char *buf);
//deal with  write
static void do_write(int epollfd, int fd, char *buf);
//change event
static void change_event(int epolled, int fd, int state, int op);



int main()
{
    printf("EPOLL_CTL_ADD is %d\n", EPOLL_CTL_ADD);
    printf("EPOLL_CTL_DEL is %d\n", EPOLL_CTL_DEL);
    printf("EPOLL_CTL_MOD is %d\n", EPOLL_CTL_MOD);
    int listenfd;
    listenfd = socket_bind(IPADDRESS, PORT);
    listen(listenfd, LISTENQ);
    do_epoll(listenfd);
    puts("epoll server end");
    return 0;
}

//bind socket
static int socket_bind(const char* ip, int port)
{ 
    int listenfd;
    struct sockaddr_in serveraddr;
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if (listenfd == -1)
    {
       perror("create socket failed\n");
       exit(EXIT_FAILURE);
    }
    //please do not forget bzero serveraddr
    bzero(&serveraddr, sizeof(serveraddr));
    //init serveraddr
    serveraddr.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &serveraddr.sin_addr);
    //please do not forget this is htons(port). not is port
    serveraddr.sin_port = htons(port);
    if (bind(listenfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) == -1)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    return listenfd;
}

//io epoll
static void do_epoll(int listenfd)
{
    int epollfd;
    struct epoll_event events[EPOLLEVENTS];
    int  result;
    char buf[MAXSIZE];
    memset(buf, 0, MAXSIZE);
    //create epollfd 
    epollfd = epoll_create(FDSIZE);
    //add listen listenfd event
    change_event(epollfd, listenfd, EPOLLIN, EPOLL_CTL_ADD);
    while (1)
    {
         //get has prepared fd events
         result = epoll_wait(epollfd, events, EPOLLEVENTS, -1);
         printf("need deal with events is %d\n", result);
         handle_events(epollfd, events, result, listenfd, buf); 
    }
    close(epollfd);
   
}

//deal with events
static void handle_events(int epollfd, struct epoll_event *events, int num, int listenfd, char *buf)
{
    int i;
    int fd;
    //foreach
    for (i = 0; i < num; ++i)
    {
         fd = events[i].data.fd;
         //deal with events by fd
         if ((fd == listenfd) && (events[i].events & EPOLLIN)) 
         {
            puts("has go in handle_accpet");
            handle_accpet(epollfd, listenfd);
         }
         else if (events[i].events & EPOLLIN)
         { 
            puts("do read");  
            do_read(epollfd, fd, buf);
 	 }
         else if (events[i].events & EPOLLOUT)
         {
            puts("do write");
            do_write(epollfd, fd, buf);
         }
    }

}
//deal with accpet events
static void handle_accpet(int epolled, int listenfd)
{
    int clifd;
    struct sockaddr_in cli_addr;
    socklen_t length = sizeof(cli_addr);
    clifd = accept(listenfd, (struct sockaddr*)&cli_addr, &length);
//    if (clifd < 0) {
    if (clifd == -1)
        perror("accept failed\n");
//      exit(EXIT_FAILURE);
//    }  
    else 
    {
        printf("accpet a new client:ip is %s and portsi %d\n", inet_ntoa(cli_addr.sin_addr), cli_addr.sin_port);
        //add client event
        change_event(epolled, clifd, EPOLLIN, EPOLL_CTL_ADD);
    }
}
//deal with read
static void do_read(int epollfd, int fd, char *buf)
{
    int nread;
    nread = read(fd, buf, MAXSIZE);
    if (nread == -1) 
    {
        perror("read data failed\n");
        close(fd);
        //delelet event
        change_event(epollfd, fd, EPOLLIN, EPOLL_CTL_DEL);        
    }
    else if (nread == 0)
    {
        fprintf(stderr, "client close\n");
        close(fd);
        //delete event
        change_event(epollfd, fd, EPOLLIN, EPOLL_CTL_DEL);        
    }
    else 
    {
        printf("read message is  %s\n", buf);
        //change event. from read to write
        change_event(epollfd, fd, EPOLLOUT, EPOLL_CTL_MOD);
    }
}
//deal with  write
static void do_write(int epollfd, int fd, char *buf)
{
    int nwrite;
    nwrite = write(fd, buf, strlen(buf));
    if (nwrite == -1)
    {
        perror("write falied\n");
        close(fd);
        change_event(epollfd, fd, EPOLLOUT, EPOLL_CTL_DEL);
    }
    else 
    {
        change_event(epollfd, fd, EPOLLIN, EPOLL_CTL_MOD);
        memset(buf, 0, MAXSIZE);
    }
}

//change event
static void change_event(int epollfd, int fd, int state, int op)
{
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    epoll_ctl(epollfd, op, fd, &ev);
}






   2)客户端tcp_epoll_client.c代码如下

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define MAXSIZE 1024
#define IPADDRESS "127.0.0.1"
#define SERV_PORT 8888
#define FDSIZE 1024
#define EPOLLEVENTS 20

static void handle_connection(int sockfd);
static void handle_events(int epollfd, struct epoll_event *events, int num, int sockfd, char *buf);
static void do_read(int epollfd, int fd, int sockfd, char *buf);
static void do_write(int epollfd, int fd, int sockfd, char *buf);
static void change_event(int epollfd, int fd, int state, int op);


int main()
{
    int sockfd;
    struct sockaddr_in server_addr;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) 
    {
        perror("client create socket failed\n");
 	exit(EXIT_SUCCESS);
    }
 
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERV_PORT);
    inet_pton(AF_INET, IPADDRESS, &server_addr.sin_addr);
    
    socklen_t length = sizeof(server_addr);
    if (connect(sockfd, (struct sockaddr*)&server_addr, length) < 0)
    {
        perror("clint connect failed\n");
        exit(EXIT_SUCCESS);
    }   
    //deal with connection
    handle_connection(sockfd);
    //do not forget to close sockfd
    close(sockfd);
    return 0;    
}

static void handle_connection(int sockfd)
{
    int epollfd;
    struct epoll_event events[EPOLLEVENTS];
    char buf[MAXSIZE];
    memset(buf, 0, sizeof(buf));
    int result;
    epollfd = epoll_create(FDSIZE);
    change_event(epollfd, STDIN_FILENO,EPOLLIN, EPOLL_CTL_ADD);
    while (1)
    {
       result = epoll_wait(epollfd, events, EPOLLEVENTS, -1);
       printf("clinet need deal events is %d\n", result);
       handle_events(epollfd, events, result, sockfd, buf);
    }
    //do not forget to close epollfd
    close(epollfd);
}
static void handle_events(int epollfd, struct epoll_event *events, int num, int sockfd, char *buf)
{
    int fd;
    int i;
    for (i = 0; i < num; i++) 
    {
        fd = events[i].data.fd;
        if (events[i].events & EPOLLIN)
        {
           do_read(epollfd, fd, sockfd, buf);
        }
        else if (events[i].events & EPOLLOUT)
        {
           do_write(epollfd, fd, sockfd, buf);
        }
    }
}
static void do_read(int epollfd, int fd, int sockfd, char *buf)
{
    int nread;
    nread = read(fd, buf, MAXSIZE);
    if (nread == -1) 
    {
       perror("client read fail\n");
       close(fd);
    }
    else if (nread == 0)
    {
       fprintf(stderr, "server close\n");
       close(fd);
    }
    else 
    {
        if (fd == STDIN_FILENO)
        {
            puts("do read fd == STDIN_FILENO");
            change_event(epollfd, sockfd, EPOLLOUT, EPOLL_CTL_ADD);
        }
        else 
        {
            puts("do read fd != STDIN_FILENO");
            change_event(epollfd, sockfd, EPOLLIN, EPOLL_CTL_DEL);
            change_event(epollfd, STDOUT_FILENO, EPOLLOUT, EPOLL_CTL_ADD);
        }
    }
}

static void do_write(int epollfd, int fd, int sockfd, char *buf)
{
    int nwrite;
    nwrite = write(fd, buf, strlen(buf));
    if (nwrite == -1)
    {
        perror("client write failed\n");
        close(fd);
    }
    else 
    {
        if (fd == STDOUT_FILENO)
        {  
           puts("do write fd == STDOUT_FILENO");
           change_event(epollfd, fd, EPOLLOUT, EPOLL_CTL_DEL);
        } 
        else 
        {
           puts("do write fd != STDOUT_FILENO");
           change_event(epollfd, fd, EPOLLIN, EPOLL_CTL_MOD);
        }
    }
    memset(buf, 0, MAXSIZE);
}
static void change_event(int epollfd, int fd, int state, int op)
{
    struct epoll_event ev;
    ev.events = state;
    ev.data.fd = fd;
    epoll_ctl(epollfd, op, fd, &ev);
}






5、运行结果

  服务端:
linux网络编程之用epoll实现io复用(基于tcp)_第1张图片
  客户端:
linux网络编程之用epoll实现io复用(基于tcp)_第2张图片


你可能感兴趣的:(Linux,网络编程)