int acceptConnect(int listenFd,int epollFd)
{
int sockConnect = 0;
int addrLen = 0;
struct epoll_event tempEvent;
struct sockaddr_in remoteAddr;
addrLen = sizeof(struct sockaddr_in);
sockConnect = accept(listenFd, (struct sockaddr*)&remoteAddr, &addrLen);
if ( sockConnect < 0 ) {
return -1;
}
setnonblocking(sockConnect);
tempEvent.events = EPOLLIN | EPOLLET;
tempEvent.data.fd = sockConnect;
if (epoll_ctl(epollFd, EPOLL_CTL_ADD, sockConnect, &tempEvent) < 0) {
return -1;
}
return 0;
}
int initEpollFd(int listenFd)
{
struct epoll_event ev;
int epfd = 0;
epfd = epoll_create(MAX_EPOLL_FD);
ev.events = EPOLLIN;
ev.data.fd = listenFd;
if (epoll_ctl(epfd,EPOLL_CTL_ADD,listenFd,&ev) < 0) {
return -1;
}
return epfd;
}
int initSrvSock(int port)
{
int ListenFd = 0;
struct sockaddr_in serverAddr;
int opts = 0x1;
int ret = 0;
bzero(&serverAddr, sizeof(struct sockaddr_in));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(port);
ListenFd = socket(AF_INET, SOCK_STREAM, 0);
if (ListenFd < 0) {
return -1;
}
setnonblocking(ListenFd);
ret = setsockopt(ListenFd, SOL_SOCKET, SO_REUSEADDR, &opts, sizeof(int));
if ( ret == -1) {
return -1;
}
ret = bind(ListenFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
if (ret < 0) {
return -1;
}
ret = listen(ListenFd, MAX_CONN);
if (ret < 0) {
return -1;
}
return ListenFd;
}
int processRequest()
{
int i = 0;
int epollFd = 0;
int listenFd = 0;
int nfds = 0;
static actionPar par = { 0 };
struct epoll_event events[EV_LEN];
listenFd = initSrvSock(LISTEN_PORT);
if (-1 == listenFd) {
return -1;
}
epollFd = initEpollFd(listenFd);
if (-1 == epollFd) {
return -1;
}
while (1) {
nfds = epoll_wait(epollFd, events, EV_LEN, TIMEOUT);
for ( i = 0 ; i < nfds ; i++ ) {
if ( listenFd == events[i].data.fd ) {
acceptConnect(listenFd,epollFd);
} else {
if (recvData(events[i].data.fd,par.data, sizeof(par.data)) > 0) {
par.sockFd = events[i].data.fd;
par.dataSize = strlen(par.data);
parseData(&par);
}
}
}
}
return 0;
}
阅读(4012) | 评论(0) | 转发(0) |