1 #include <iostream>
2 #include <sys/socket.h>
3 #include <sys/epoll.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <errno.h>
12
13 using namespace std;
14
15 #define MAXLINE 5
16 #define OPEN_MAX 100
17 #define LISTENQ 20
18 #define SERV_PORT 5000
19 #define INFTIM 1000
20
21 int main(int argc,char* argv[])
22 {
23 int listen_fd,connfd_fd,socket_fd,epfd,nfds;
24 ssize_t n;
25 char line[MAXLINE];
26 socklen_t clilen;
27
28 //声明epoll_event结构体的变量,ev用于注册事件,数组用于回传要处理的事件
29 struct epoll_event ev,events[20];
30 生成用于处理accept的epoll专用的文件描述符
31 epfd=epoll_create(5);
32 struct sockaddr_in clientaddr;
33 struct sockaddr_in serveraddr;
34 listen_fd = socket(AF_INET,SOCK_STREAM,0);
35 设置与要处理的事件相关的文件描述符
36 ev.data.fd = listen_fd;
37 设置要处理的事件类型
38 ev.events=EPOLLIN|EPOLLET;
39 注册epoll事件
40 epoll_ctl(epfd,EPOLL_CTL_ADD,listen_fd,&ev);
41
42 memset(&serveraddr,128); line-height:1.5!important">0,255); line-height:1.5!important">sizeof(serveraddr));
43 serveraddr.sin_family = AF_INET;
44 serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
45 serveraddr.sin_port = htons(SERV_PORT);
46
47 if (bind(listen_fd,(struct sockaddr*)&serveraddr,255); line-height:1.5!important">sizeof(serveraddr)) == -1)
48 {
49 printf("bind socket error: %s(errno: %d)n",strerror(errno),errno);
50 exit(0);
51 }
52
53 if (listen(listen_fd,LISTENQ) == - 54 {
55 exit( 56 }
57
58 for ( ; ; )
59 {
60 等待epoll事件的发生
61 nfds = epoll_wait(epfd,events,128); line-height:1.5!important">20,128); line-height:1.5!important">500);
62 处理所发生的所有事件
63 for (int i = 0; i < nfds; ++i)
64 {
65 if (events[i].data.fd == listen_fd)如果新监测到一个SOCKET用户连接到了绑定的SOCKET端口,建立新的连接。
66
67 {
68 connfd_fd = accept(listen_fd,(sockaddr *)&clientaddr,&clilen);
69 if (connfd_fd < 0){
70 perror(connfd_fd < 0");
71 exit(1);
72 }
73 char *str = inet_ntoa(clientaddr.sin_addr);
74 cout << accapt a connection from " << str << endl;
75 设置用于读操作的文件描述符
76 ev.data.fd = connfd_fd;
77 设置用于注测的读操作事件
78 ev.events = EPOLLIN|EPOLLET;
79 注册ev
80 epoll_ctl(epfd,128); line-height:1.5!important"> 81 }
82 else if (events[i].events&EPOLLIN)如果是已经连接的用户,并且收到数据,那么进行读入。
83 {
84 memset(&line,0); line-height:1.5!important">'