下面是代码,关于socket调用是自己简单封装过的 就不拿出来了,可以当伪代码看
#include <stdio.h> #include <stdlib.h> #ifndef _WIN32 #include <stdint.h> #else #if _MSC_VER > 1600 #include <stdint.h> #else #include "win-stdint.h" #endif #endif #include <time.h> #include "Socket.h" #include <sys/epoll.h> #include <errno.h> struct sData { sData():size(0) { } char buf[1024]; int size; BASE_SOCKET s; }; int main(int narg,char** args) { printf("just epoll demo server [build at %s %s]\n",__DATE__,__TIME__); int port=8768; int epfd=epoll_create1(EPOLL_CLOEXEC); if(0>epfd) { printf("epoll_create1 failed,err=%d\n",errno); return 0; } BASE_SOCKET s=GetSocket(true,true); ::Bind(s,"0.0.0.0",port,true,true); printf("bind 0.0.0.0:%d\n",port); struct epoll_event ev; ev.events=EPOLLIN; ev.data.fd=s; int ret=0; ret=epoll_ctl(epfd,EPOLL_CTL_ADD,s,&ev); if(ret)printf("epoll_ctl failed,fd=%d err=%d\n",s,errno); struct epoll_event e[64]; char buf[1024]; int size=0; while(true) { int n=epoll_wait(epfd,e,64,1000); if(n<1)continue; for(int i=0;i<n;++i) { if(e[i].data.fd==s) { string ip; BASE_SOCKET s2=::Accept(s,0,ip); if(INVALID_BASE_SOCKET==s2)continue; printf("accep fd=%d from %s\n",s2,ip.c_str()); ev.events=EPOLLIN; sData* cur=new sData(); cur->s=s2; ev.data.ptr=cur; ret=epoll_ctl(epfd,EPOLL_CTL_ADD,cur->s,&ev); if(ret)printf("epoll_ctl add failed,fd=%d err=%d\n",cur->s,errno); continue; } if(e[i].events&EPOLLIN) { sData* cur=(sData*)e[i].data.ptr; cur->size=::Recv(cur->s,cur->buf,sizeof(cur->buf)); if(cur->size<1) { ret=epoll_ctl(epfd,EPOLL_CTL_DEL,cur->s,&e[i]); if(ret)printf("epoll_ctl del failed,fd=%d err=%d\n",cur->s,errno); CloseSocket(cur->s); printf("fd=%d close\n",cur->s); delete cur; continue; } printf("fd=%d recv %d\n",cur->s,cur->size); e[i].events=EPOLLOUT; ret=epoll_ctl(epfd,EPOLL_CTL_MOD,cur->s,&ev); if(ret)printf("epoll_ctl mod write failed,fd=%d err=%d\n",cur->s,errno); } if(e[i].events&EPOLLOUT) { sData* cur=(sData*)e[i].data.ptr; ret=::Send(cur->s,cur->buf,cur->size,0); printf("fd=%d send %d\n",cur->s,ret); if(ret<1) { ret=epoll_ctl(epfd,EPOLL_CTL_DEL,cur->s,&e[i]); if(ret)printf("epoll_ctl del failed,fd=%d err=%d\n",cur->s,errno); CloseSocket(cur->s); printf("fd=%d close\n",cur->s); delete cur; continue; } e[i].events=EPOLLIN; ret=epoll_ctl(epfd,EPOLL_CTL_MOD,cur->s,&ev); if(ret)printf("epoll_ctl mod write failed,fd=%d err=%d\n",cur->s,errno); } if(e[i].events&EPOLLHUP) { sData* cur=(sData*)e[i].data.ptr; ret=epoll_ctl(epfd,EPOLL_CTL_DEL,cur->s,&e[i]); if(ret)printf("epoll_ctl del failed,fd=%d err=%d\n",cur->s,errno); CloseSocket(cur->s); printf("fd=%d close\n",cur->s); delete cur; continue; } } } close(epfd); return 0; }