linux下使用select异步IO模式实现客户端

【linux下使用select异步IO模式实现客户端】目的:使用select fd_set FD_SET FD_ISSET FD_ZERO

#include// memset #include #include #include #ifdef HAVE_NETINET_IN_H #include #endif#define ERR_EXIT(m)\ do\ {\ perror(m); \ exit(EXIT_FAILURE); \ }while(0)struct packet { int len; char buf[1024]; }; ssize_t readn(int fd,void *buf,size_t count) { size_t nleft = count; ssize_t nread; char *bufp = (char*)buf; while(nleft>0) { nread = read(fd,bufp,nleft); if(nread <0) { if(errno = EINTR) { return -1; } } else if(nread == 0) { break; } else { bufp += nread; nleft -= nread; }} }ssize_t written(int fd,void *buf,size_t count) { //printf("%d",count); size_t nleft = count; ssize_t nwritten; char *bufp = (char*)buf; //fputs(bufp,stdout); while(nleft>0) { nwritten = write(fd,bufp,nleft); if(nwritten <0) { if(errno = EINTR) { return -1; } } else if(nwritten == 0) { continue; } else { bufp += nwritten; nleft= nleft -nwritten; //printf("%d",nleft); }} } ssize_t recv_peek(int sockfd,void *buf,size_t len) { while(1) { int ret = recv(sockfd,buf,len,MSG_PEEK); if(ret == -1 && errno==EINTR) { continue; } else { return ret; } } }ssize_t readline(int sockfd,void *buf,size_t maxline) { int ret; int nread; char *bufp =(char*)buf; int nleft = maxline; while(1) { ret = recv_peek(sockfd,bufp,nleft); if(ret < 0) { return ret; } else if(ret ==0) { return ret; } else { nread = ret; int i; for(i=0; i nleft) { exit(EXIT_FAILURE); } nleft -= nread; ret = readn(sockfd,bufp,nread); if(ret != nread) { exit(EXIT_FAILURE); }bufp += nread; } return -1; }}int main(void) { int sock; if((sock =socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))<0) { ERR_EXIT("ERROR"); } struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port = htons(5188); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr))< 0) { ERR_EXIT("connect"); } fd_set rset; FD_ZERO(&rset); int nready; int maxfd; int fd_stdin = fileno(stdin); if(fd_stdin > sock) maxfd = fd_stdin; else maxfd = sock; char sendbuf[1024] ={0}; char recvbuf[1024] ={0}; while(1) { FD_SET(fd_stdin,&rset); FD_SET(sock,&rset); nready = select(maxfd+1,&rset,NULL,NULL,NULL); if(nready ==-1) ERR_EXIT("SELECT"); if(nready==0) continue; if(FD_ISSET(sock,&rset)) { int ret = readline(sock,recvbuf,sizeof(recvbuf)); if(ret == -1) ERR_EXIT("readline"); else if(ret ==0) { printf("server close\n"); break; } fputs(recvbuf,stdout); memset(recvbuf,0,sizeof(recvbuf)); } if(FD_ISSET(fd_stdin,&rset)) { if( fgets(sendbuf,sizeof(sendbuf),stdin)==NULL) break; written(sock,sendbuf,strlen(sendbuf)); memset(sendbuf,0,sizeof(sendbuf)); } }return 0; }

    推荐阅读