epoll支持linux内核 类Unix如mac是不支持的
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<fcntl.h>
#include<sys/epoll.h>
void addfd(int epollfd,int fd){
struct epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN | EPOLLET;
epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&event);
//设置非阻塞
int old_option = fcntl(fd,F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd,F_SETFL,new_option);
}
int main(){
int epollfd;
int server_sockfd,client_sockfd;
int server_len,client_len;
struct sockaddr_in server_address,client_address;
int result;
char ch[1024];
server_sockfd = socket(AF_INET,SOCK_STREAM,0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(8888);
server_len = sizeof(server_address);
bind(server_sockfd,(struct sockaddr *)&server_address,server_len);
listen(server_sockfd,5);
struct epoll_event events[1024];
epollfd = epoll_create(5);
//把服务器端 添加到epollfd指定的 epoll内核时间表中
addfd(epollfd,server_sockfd);
while(1){
printf("server waiting\n");
//-1不超时 返回发送的时间数量
int ret = epoll_wait(epollfd,events,1024,-1);
int i = 0;
for(i; i< ret;i++){
int sockfd = events[i].data.fd;
//说明是一个新的链接
if(sockfd == server_sockfd){
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address,&client_len);
printf("收到一个新的链接\n");
addfd(epollfd,client_sockfd);
}else{
int len = read(sockfd,&ch,1024);
write(sockfd,&ch,len);
if(strncasecmp(ch,"stop",4) == 0){
close(sockfd);
}
}
}
}
}