#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/tcp.h>
#include<unistd.h>
#include <arpa/inet.h>
#include <errno.h>
int main() {
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd < 0) return -1;
struct sockaddr_in serv_addr;
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(6016);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0) {
perror("bind fail");
return -2;
}
if(listen(sockfd, 5) < 0) {
perror("listen error");
return -3;
}
fd_set rfds,rset;
FD_ZERO(&rfds);
FD_SET(sockfd,&rfds);
int maxfd = sockfd+1;
while(1) {
rset = rfds;
//返回值 有多个IO有可读事件产生或者内核有多个IO数据准备就绪
//int maxfdp是一个整数值,是指集合中所有文件描述符的范围,即所有文件描述符的最大值加1,不能错!在Windows中这个参数的值无所谓,可以设置不正确。
int nready = select(maxfd,&rset,NULL,NULL,NULL);
if(nready <0)continue;
if(FD_ISSET(sockfd,&rset)) {
struct sockaddr_in clientaddr;
socklen_t client_len = sizeof(clientaddr);
int clientfd = accept(sockfd,(struct sockaddr*)&clientaddr,&client_len);
if(clientfd <0) continue;
FD_SET(clinetfd,&rfds);
maxfd = clientfd+1;
printf("sockfd:%d,max_fd:%d,clientfd:%d\n",sockfd,maxfd,clientfd);
if(--nready ==0)continue;
}
int i = 0;
for(i = sockfd+1 ; i<maxfd ; i++){
if(FD_ISSET(i,&rset)){
char buffer[1024]={0};
int ret = recv(i,buffer,1024,0);
if(ret < 0) {
if(errno == EAGAIN || errno == EWOULDBLOCK) {//多线程和多进程时--tcb块的recvbuf里面的数据在其他线程已经读过了
printf("read all data");
continue;
}else{
FD_CLR(i,&rfds);
close(i);
}
}else if(ret == 0){ //客户端断开连接
printf(" disconnect %d\n", i);
FD_CLR(i, &rfds);
close(i);
break;
}else {
printf("Recv: %s, %d Bytes\n", buffer, ret);
}
if(--nready == 0)break;
}
}
}
}