一个简单的epoll demo ,同时接受多个客户端连接,并把接收到的字符串转化为大写字母返回给客户端
1 #include<stdio.h> 2 #include<arpa/inet.h> 3 #include<sys/epoll.h> 4 #include<unistd.h> 5 #include<ctype.h> 6 #define MAXLEN 1024 7 #define SERV_PORT 8000 8 #define MAX_OPEN_FD 1024 9 10 int main(int argc,char *argv[]) 11 { 12 int listenfd,connfd,efd,ret; 13 char buf[MAXLEN]; 14 struct sockaddr_in cliaddr,servaddr; 15 socklen_t clilen = sizeof(cliaddr); 16 struct epoll_event tep,ep[MAX_OPEN_FD]; 17 18 listenfd = socket(AF_INET,SOCK_STREAM,0); 19 20 servaddr.sin_family = AF_INET; 21 servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 22 servaddr.sin_port = htons(SERV_PORT); 23 bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); 24 listen(listenfd,20); 25 // 创建一个epoll fd 26 efd = epoll_create(MAX_OPEN_FD); 27 tep.events = EPOLLIN;tep.data.fd = listenfd; 28 // 把监听socket 先添加到efd中 29 ret = epoll_ctl(efd,EPOLL_CTL_ADD,listenfd,&tep); 30 // 循环等待 31 for (;;) 32 { 33 // 返回已就绪的epoll_event,-1表示阻塞,没有就绪的epoll_event,将一直等待 34 size_t nready = epoll_wait(efd,ep,MAX_OPEN_FD,-1); 35 for (int i = 0; i < nready; ++i) 36 { 37 // 如果是新的连接,需要把新的socket添加到efd中 38 if (ep[i].data.fd == listenfd ) 39 { 40 connfd = accept(listenfd,(struct sockaddr*)&cliaddr,&clilen); 41 tep.events = EPOLLIN; 42 tep.data.fd = connfd; 43 ret = epoll_ctl(efd,EPOLL_CTL_ADD,connfd,&tep); 44 } 45 // 否则,读取数据 46 else 47 { 48 connfd = ep[i].data.fd; 49 int bytes = read(connfd,buf,MAXLEN); 50 // 客户端关闭连接 51 if (bytes == 0){ 52 ret =epoll_ctl(efd,EPOLL_CTL_DEL,connfd,NULL); 53 close(connfd); 54 printf("client[%d] closed\n", i); 55 } 56 else 57 { 58 for (int j = 0; j < bytes; ++j) 59 { 60 buf[j] = toupper(buf[j]); 61 } 62 // 向客户端发送数据 63 write(connfd,buf,bytes); 64 } 65 } 66 } 67 } 68 return 0; 69 }
时间: 2024-10-11 20:06:03