Linux下IP v6 tcp客户端源码示例

       while (1)  
       {  
              //----------set last time---------  
              tv.tv_sec=600;  
              tv.tv_usec=0;  
                
              FD_ZERO(&readfd);  
              // 将标准输入和与服务连接的文件句柄读事件加入SET  
              FD_SET(0,&readfd);  
              FD_SET(sockfd,&readfd);  
                
              // 检查是否有读事件发生  
              if ( select( sockfd+1, &readfd, NULL, NULL, &tv) <= 0 )  
              {  
                     fprintf(stderr,"\n time out\n");  
                     break;  
              }  
                
              // 如果标准输入中有数据可读,则从其中读取数据,并向服务器发送  
              if ( FD_ISSET(0,&readfd) )  
              {  
                     if( (n = read(0, send_buf, MAXSIZE-1)) <= 0 )  
                     {  
                            break;  
                     }  
                       
                     send_buf[n]='\n';  
                     if ( send( sockfd, send_buf, n, 0) <= 0)  
                     {  
                            perror("send");  
                            break;  
                     }  
              }  
                
              // 如果有从服务器发送过来的数据,则将其读取出来,并输出到标准输出  
              if ( FD_ISSET(sockfd, &readfd) )  
              {  
                     if ( ( n = recv(sockfd, recv_buf, MAXSIZE-1, 0)) <= 0 )  
                     {  
                            fprintf(stderr,"connection closed.\n");  
                            exit(1);  
                     }  
                       
                     recv_buf[n]='\0';  
                     printf("recved:%s", recv_buf);  
                     fflush(stdout);  
              }  
       }  
       close(sockfd);  
       return 0;  
}

相关推荐