epoll服务器模型

时间:2022-01-29 00:17:23

server:

#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/epoll.h>
#include<errno.h>
#include<sys/socket.h>
#include<sys/types.h>

#define maxline 80000
#define port 8000
#define openmax 10000
#define backlog 10
#define buflen 1024a

int main(int argc ,char* argv[]){
	
	struct sockaddr_in servaddr,clientaddr;
	socklen_t client_len = sizeof(clientaddr);

	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	int listenfd = socket(AF_INET,SOCK_STREAM,0);

	if(listenfd<0){
		printf("socket failed\n");
		exit(1);
	}

	int ret = bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));

	if(ret <0){
		printf("bind failed\n");
		exit(1);
	}

	ret = listen(listenfd,backlog);
	
	int efd = epoll_create(openmax);
	struct epoll_event tep,ep[openmax];
	tep.events = EPOLLIN;
	tep.data.fd = listenfd;
	int res = epoll_ctl(efd,EPOLL_CTL_ADD,listenfd,&tep);
	int nready;
	int i;
	int connfd,sockfd;
	char str[buflen];
	int num = 0;
	int len ;
	char buf[buflen];
	while(1){
		nready = epoll_wait(efd,ep,openmax,-1);
		for(i = 0;i<nready;i++){
			if(!(ep[i].events & EPOLLIN)){
				continue;
			}
			if(ep[i].data.fd == listenfd){
				connfd = accept(listenfd,(struct sockaddr*)&clientaddr,&client_len);
				printf("received form %s \t port:%d\n",inet_ntop(AF_INET,&clientaddr.sin_addr,str,sizeof(str)),ntohs(clientaddr.sin_port));
				printf("cfd %d \t client \t %d\n",connfd,++num);
				tep.events = EPOLLIN;
				tep.data.fd = connfd;

				res = epoll_ctl(efd,EPOLL_CTL_ADD,connfd,&tep);
			}
			else{
				sockfd = ep[i].data.fd;
				len = read(sockfd,buf,buflen);
				if(len == 0){
					//client close
					res = epoll_ctl(efd,EPOLL_CTL_DEL,sockfd,NULL);
					if(res == -1){
						printf("epoll fialed\n");
						exit(1);
					}
					close(sockfd);
					printf("client[%d] closed connection\n",sockfd);
					}
				else if(len <0){
						printf("epoll failed \n");
						epoll_ctl(efd,EPOLL_CTL_DEL,sockfd,NULL);
						close(sockfd);
					}
				
			 	
			    else{
					int j;
					for(j= 0;j<len;j++){
						buf[j] = toupper(buf[j]);
					}
					write(STDOUT_FILENO,buf,len);
					write(sockfd,buf,len);
				}
			}
		}
	}
	close(listenfd);
	close(efd);
	return 0;
}