#include <stdlib.h> #include <dirent.h> #include <time.h> #include <unistd.h> #include <dirent.h> #include <sys/types.h> #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <error.h> #include <string.h> int readnet( int sockid, register char *ptr, short nbytes) { int nleft=0,nread=0; fd_set Readyfd; struct timeval timeout; int ret; nleft=nbytes; FD_ZERO(&Readyfd); FD_SET(sockid, &Readyfd); timeout.tv_sec = 0; timeout.tv_usec = 500000;//0.5秒 ret = select(sockid+1, NULL, &Readyfd, NULL, &timeout); if(ret<=0) { return -1; } nleft=nbytes; while(nleft > 0) { nread = read(sockid,ptr,nleft); if (nread <= 0 ) { return (nread); } nleft -=nread; ptr +=nread; } return nbytes-nleft; } int Client() { char buf[200] = {0}; int iSockfd = socket(PF_INET,SOCK_STREAM,0);/*1. 准备socket*/ if(iSockfd == -1) { return -1; } struct sockaddr_in addr; addr.sin_family = PF_INET; addr.sin_port = htons(17777); inet_aton("127.0.0.1",&addr.sin_addr); //unsigned long ul = 1; //ioctl(iSockfd, FIONBIO, &ul); //设置为非阻塞模式 struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 500000;//0.5秒 setsockopt(iSockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); fd_set Readyfd; int ret; int iNum = 0; while(-1 == connect(iSockfd,(struct sockaddr*)&addr, sizeof(addr))) { iNum ++; printf("--------%d 次重连\n",iNum); sleep(1); if(iNum == 10) { printf("-----------连接失败\n"); return -1; } } ret = select(iSockfd, NULL, &Readyfd, NULL, &timeout); //printf("--------Connect =%d\n",iRes); printf("--------select =%d\n",ret); write(iSockfd,(char *)"hello world ,I‘m Client", 100); //ret = select(iSockfd, NULL, &Readyfd, NULL, &timeout); printf("---------ret=%d\n",ret); int i; for( i=0;i<6;i++) { if(ret == 0) { int iRet = read(iSockfd, buf, 100); printf("---1----超时 次数:%d\n",i); if(iRet <= 0) { continue; } else { break; } } if(ret>0) { int iSet = FD_ISSET(iSockfd, &Readyfd); int iRet = read(iSockfd, buf, 100); printf("---2----超时 次数:%d\n",i); } } //int iRet = read(iSockfd, buf, 100); printf("-------buf=%s\n",buf); printf("--------------函数结束--------\n"); return 0; } int main() { Client(); return 0; }
时间: 2024-11-14 18:27:19