生活随笔
收集整理的這篇文章主要介紹了
Linux网络编程——tcp并发服务器(epoll实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
https://blog.csdn.net/lianghe_work/article/details/46551871
通過epoll實現tcp并發回執服務器(客戶端給服務器發啥,服務器就給客戶端回啥)
代碼如下:
#include <string.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/select.h>#include <sys/time.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <sys/epoll.h>#include <errno.h>#define OPEN_MAX 100 int main(int argc, char *argv[]){ struct epoll_event event; struct epoll_event wait_event; int sockfd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in my_addr;bzero(&my_addr, sizeof(my_addr));my_addr.sin_family = AF_INET;my_addr.sin_port = htons(8001);my_addr.sin_addr.s_addr = htonl(INADDR_ANY);bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr)); listen(sockfd, 10); int fd[OPEN_MAX]; int i = 0, maxi = 0;memset(fd,-1, sizeof(fd));fd[0] = sockfd; int epfd = epoll_create(10); if( -1 == epfd ){ perror ("epoll_create"); return -1; } event.data.fd = sockfd; event.events = EPOLLIN; int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &event); if(-1 == ret){ perror("epoll_ctl"); return -1; } while(1){ ret = epoll_wait(epfd, &wait_event, maxi+1, -1); if(( sockfd == wait_event.data.fd ) && ( EPOLLIN == wait_event.events & EPOLLIN ) ){ struct sockaddr_in cli_addr; int clilen = sizeof(cli_addr); int connfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen); for(i=1; i<OPEN_MAX; i++){ if(fd[i] < 0){fd[i] = connfd; event.data.fd = connfd; event.events = EPOLLIN; ret = epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &event); if(-1 == ret){ perror("epoll_ctl"); return -1; } break;}} if(i > maxi)maxi = i; if(--ret <= 0) continue;} for(i=1; i<=maxi; i++){ if(fd[i] < 0) continue; if(( fd[i] == wait_event.data.fd ) && ( EPOLLIN == wait_event.events & (EPOLLIN|EPOLLERR) )){ int len = 0; char buf[128] = ""; if((len = recv(fd[i], buf, sizeof(buf), 0)) < 0){ if(errno == ECONNRESET){close(fd[i]);fd[i] = -1;} elseperror("read error:");} else if(len == 0){close(fd[i]);fd[i] = -1;} elsesend(fd[i], buf, len, 0); if(--ret <= 0) break;}}} return 0;}運行結果:
源碼下載:
總結
以上是生活随笔為你收集整理的Linux网络编程——tcp并发服务器(epoll实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。