Skip to content

Instantly share code, notes, and snippets.

@wilem
Created March 14, 2014 02:02
Show Gist options
  • Save wilem/9540882 to your computer and use it in GitHub Desktop.
Save wilem/9540882 to your computer and use it in GitHub Desktop.
void epoll_server()
{
for(; ;) {
nfds = epoll_wait(epfd, events, 20/*maxevents*/, 500/*timeout*/);
for(i = 0; i < nfds; ++i) {
// 如果是主socket的事件,则表示有新的连接
if (events[i].data.fd == listenfd) {
connfd = accept(listenfd,
(sockaddr *) &clientaddr,
&clilen);
// 将新的fd添加到epoll的监听队列中
ev.data.fd = connfd;
ev.events = EPOLLIN|EPOLLET;
epoll_ctl(epfd, EPOLL_CTL_ADD, connfd, &ev);
} else if (events[i].events & EPOLLIN) { //接收到数据
if ((sockfd = events[i].data.fd) < 0)
continue;
n = read(sockfd, line, MAXLINE); //< 0 //读
ev.data.ptr = md;
// md为自定义类型,添加数据
ev.events = EPOLLOUT|EPOLLET;
// 修改标识符,等待下一个循环时发送数据,异步处理的精髓
epoll_ctl(epfd, EPOLL_CTL_MOD, sockfd, &ev);
} else if (events[i].events & EPOLLOUT) {
// async write?
struct myepoll_data* md;
md = (myepoll_data*)events[i].data.ptr;
sockfd = md->fd;
send(sockfd, md->ptr, strlen((char*)md->ptr), 0);
ev.data.fd = sockfd;
ev.events = EPOLLIN|EPOLLET;
// 修改标识符,等待下一个循环时接收数据
epoll_ctl(epfd, EPOLL_CTL_MOD, sockfd, &ev);
} else {
// 其他情况的处理
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment