#define _FNU_SOURCE
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAX_FD 128
#define DATALEN 1024
#define EPOLLSIZE 5
#define LT 0
#define ET 1
int InitSocket()
{
int sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)return -1;
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family=AF_INET;
saddr.sin_port=htons(6000);
saddr.sin_addr.s_addr=inet_addr("127.0.0.1");
int res=bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
if(res==-1)
{
printf("bind errno\n");
return -1;
}
res=listen(sockfd,5);
if(res==-1)
{
printf("listen errno\n");
return -1;
}
return sockfd;
}
void SetNoWait(int fd)
{
int old_option=fcntl(fd,F_GETFL);
int new_option=old_option | O_NONBLOCK;
fcntl(fd,F_SETFL,new_option);
}
void CloseClient(int epfd,int fd)
{
close(fd);
printf("A Clien is close\n");
if(epoll_ctl(epfd,EPOLL_CTL_DEL,fd,NULL)==-1)
{
printf("epoll_ctl del error");
}
}
void GetClientLink(int sockfd,int epfd,int flag)
{
struct sockaddr_in caddr;
socklen_t len=sizeof(caddr);
int c =accept(sockfd,(struct sockaddr*)&caddr,&len);
if(c<0)
{
printf("Client Link error\n");
return;
}
struct epoll_event ev;
ev.data.fd=c;
if(flag)
{
ev.events=EPOLLIN | EPOLLRDHUP | EPOLLET;
SetNoWait(c);
}
else
{
ev.events=EPOLLIN | EPOLLRDHUP;
}
if(epoll_ctl(epfd,EPOLL_CTL_ADD,c,&ev)==-1)
{
printf("epoll_ctl add error\n");
}
}
void LTDealClientData(int epfd,int fd)
{
char buff[DATALEN]={
0};
int n=recv(fd,buff,DATALEN-1,0);
if(n<=0)
{
CloseClient(epfd,fd);
return;
}
printf("%d:%s\n",fd,buff);
send(fd,"OK",2,0);
}
void ETDealClientData(int epfd,int fd)
{
while(1)
{
char buff[DATALEN]={
0};
int n= recv(fd,buff,DATALEN-1,0);
if(n==-1)
{
if(errno==EAGAIN || errno==EWOULDBLOCK)
{
printf("read later\n");
break;
}
else
{
CloseClient(epfd,fd);
break;
}
}
else if(n==0)
{
CloseClient(epfd,fd);
break;
}
else
{
printf("%d:%s\n",fd,buff);
send(fd,"OK",2,0);
}
}
}
void DealReadyEvent(struct epoll_event *events,int n,int sockfd,int epfd)
{
int i=0;
for(;i<n;i++)
{
int fd=events[i].data.fd;
if(fd==sockfd)
{
GetClientLink(sockfd,epfd,LT);
}
else if(events[i].events & EPOLLRDHUP)
{
CloseClient(epfd,fd);
}
else if(events[i].events & EPOLLIN)
{
LTDealClientData(epfd,fd);
}
else
{
printf("error\n");
}
}
}
int main()
{
int sockfd=InitSocket();
assert(sockfd!=-1);
int epfd=epoll_create(EPOLLSIZE);
assert(epfd!=-1);
struct epoll_event ev;
ev.data.fd=sockfd;
ev.events=EPOLLIN;
if(epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&ev)==-1)
{
printf("epoll_ctl add error\n");
exit(0);
}
while(1)
{
struct epoll_event events[MAX_FD];
int n=epoll_wait(epfd,events,MAX_FD,2000);
if(n<0)
{
printf("epoll_wait error\n");
continue;
}
else if(n==0)
{
printf("已超时\n");
continue;
}
else
{
DealReadyEvent(events,n,sockfd,epfd);
}
}
}