select.c:
#include <myhead.h>#define ERR_MSG(msg) do{\fprintf(stderr,"__%d__:",__LINE__);\perror(msg);\
}while(0)#define IP "192.168.1.3"
#define PORT 8888int main(int argc, const char *argv[])
{//创建报式套接字socketint sfd=socket(AF_INET,SOCK_STREAM,0);if(-1==sfd){ERR_MSG("socket error");return -1;}printf("socket success\n");//允许端口快速复用setsockoptint reuse=1;if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))){ERR_MSG("setsockopt error");return -1;}//定义一个地址结构体struct sockaddr_in sin;sin.sin_family = AF_INET;sin.sin_port = htons(PORT);sin.sin_addr.s_addr = inet_addr(IP);//将套接字和IP、端口绑定bindif(-1==bind(sfd,(struct sockaddr*)&sin,sizeof(sin))){ERR_MSG("bind error");return -1;}printf("bind success\n");//将套接字设置成被动监听状态if(-1==listen(sfd,128)){ERR_MSG("listen error");return -1;}int newfd=-1;fd_set readfds,tempfds;FD_ZERO(&readfds);FD_ZERO(&tempfds);FD_SET(0,&readfds);FD_SET(sfd,&readfds);int maxfd=sfd;struct sockaddr_in saveCin[1024];int s_res=0;ssize_t res=0;char buf[128]="";struct sockaddr_in cin;socklen_t addrlen=sizeof(cin);while(1){tempfds=readfds;s_res=select(maxfd+1,&tempfds,NULL,NULL,NULL);if(-1==s_res){ERR_MSG("select error");return -1;}else if(0==s_res){printf("time out...\n");return -1;}for(int i=0;i<=maxfd;i++){if(!FD_ISSET(i,&tempfds)){continue;}if(0==i){printf("触发键盘输入事件>>>\n");bzero(buf,sizeof(buf));fgets(buf,sizeof(buf),stdin);buf[strlen(buf)-1]=0;printf(":%s\n",buf);}else if(sfd==i){printf("触发客户端连接事件>>>\n");if((newfd=accept(sfd,(struct sockaddr*)&cin,&addrlen)) == -1){ERR_MSG("accept");return -1;}printf("[%s:%d] newfd=%d 连接成功\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);saveCin[newfd]=cin;FD_SET(newfd,&readfds);maxfd = maxfd>newfd ? maxfd : newfd;}else{printf("触发客户端交互事件>>>\n");bzero(buf,sizeof(buf));res = recv(i,buf,sizeof(buf),0);if(-1 == res){ERR_MSG("recv");return -1;}else if(0 == res){printf("[%s:%d] newfd=%d 下线了\n",inet_ntoa(saveCin[i].sin_addr),ntohs(saveCin[i].sin_port),i);close(i);FD_CLR(i,&readfds);while(FD_ISSET(maxfd,&readfds) == 0 && maxfd-->=0);continue;}printf("[%s:%d] newfd=%d : %s\n",inet_ntoa(saveCin[i].sin_addr),ntohs(saveCin[i].sin_port),i,buf);strcat(buf,"*-*");if(send(i,buf,sizeof(buf),0) == -1){ERR_MSG("send");return -1;}printf("发送成功\n");}}}close(sfd);return 0;
}