/**********************hsj**************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/select.h>
#include<sys/types.h>
#include<sys/epoll.h>
#define SERPORT 8000
#define MAXFD 1025
void sys_err(char* cur){
perror(cur);
exit(1);
}
int main(int argc, char* argv[]){
socklen_t addrlen;
int cfd;
int i;
struct sockaddr_in seraddr, cliaddr;
addrlen = sizeof(cliaddr);
char dst[64];
char buf[1024];
int readret;
int lfd = socket(AF_INET, SOCK_STREAM, 0);
if(lfd == -1){
sys_err("socket error");
}
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(SERPORT);
seraddr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(lfd, (struct sockaddr*)&seraddr, sizeof(seraddr));
if(ret == -1){
sys_err("bind error");
}
int lis_ret = listen(lfd, 64);
if(lis_ret == -1){
sys_err("listen error");
}
int epfd = epoll_create(64);
struct epoll_event event, events[MAXFD];
event.events = EPOLLIN;
event.data.fd = lfd;
epoll_ctl(epfd, EPOLL_CTL_ADD,lfd,&event);
while(1){
int epollret = epoll_wait(epfd, events, MAXFD, -1);
if(epollret < 0){
sys_err("epoll_wait error");
}
for(i = 0; i < epollret; i++){
if(events[i].data.fd == lfd &&(events[i].events & EPOLLIN)){
cfd = accept(lfd , (struct sockaddr*)&cliaddr, &addrlen);
printf("新的客户端建立好连接,IP:%s,PORT:%d\n",inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr,dst,sizeof(dst) ),ntohs(cliaddr.sin_port));
event.data.fd = cfd;
event.events = EPOLLIN;
epoll_ctl(epfd, eEPOLL_CTL_ADD, cfd,&event);
}
else{
if(events[i].events & EPOLLIN){
readret = read(events[i].data.fd, buf, sizeof(buf));
if(readret < 0){
sys_err("read error");
}
else if(readret == 0){
printf("客户端断开连接cfd:%d\n",events[i].data.fd);
epoll_ctl(epfd, EPOLL_CTL_DEL,events[i].data.fd,NULL);
close(events[i].data.fd);
}
else{
write(STDOUT_FILENO, buf, readret);
write(events[i].data.fd, buf, readret);
}
}
}
}
}
return 0;
}
/***************************************************/
|