#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <strings.h>
#define EPOLL_RUN_TIMEOUT 1000
#define MAXEVENTS 50
int got_connect(fd) {
printf("got data\n");
return 0;
}
int main(int argc, char *argv[]){
if(argc<2){
printf("Usage: %s <port>\n",argv[0]);
return -1;
}
int port=atoi(argv[1]);
int epfd = epoll_create(512);
int nfds, cs, i;
struct epoll_event ev, *events;
struct sockaddr_in serv, cli;
int connected_fd;
int listenfd=socket(AF_INET, SOCK_STREAM, 0);
bzero(&serv,sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port = htons(port);
bind(listenfd,(struct sockaddr*)&serv,sizeof(serv));
listen(listenfd, 50);
ev.events = EPOLLIN | EPOLLET | EPOLLHUP;
ev.data.fd = listenfd;
epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev);
int addrlen = sizeof(cli);
while(1){
nfds = epoll_wait(epfd,events,MAXEVENTS,EPOLL_RUN_TIMEOUT);
if(nfds<0){
printf("epoll_wait error\n");
return -1;
}
for (i=0;i<nfds;++i){
if(events[i].data.fd == listenfd){
connected_fd = accept(listenfd, (struct sockaddr *) &cli,&addrlen);
printf("addr: %s\n",inet_ntoa(cli.sin_addr.s_addr));
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = connected_fd;
epoll_ctl(epfd, EPOLL_CTL_ADD, connected_fd, &ev);
}
else{
got_connect(events[i].data.fd);
}
}
}
close(epfd);
return 0;
}
Сцылки по теме:
http://www.kegel.com/c10k.html
http://www.monkey.org/~provos/libevent/
http://www.xmailserver.org/linux-patches/nio-improve.html
Комментариев нет:
Отправить комментарий