使用SO_RCVTIMEO套接字選項為recvfrom設置超時
阿新 • • 發佈:2017-11-19
stdout struct errno tde col include spa eval div
1 #include"apue.h" 2 void do_cli(FILE* fp,int sockfd,const (SA*)pserveraddr,socklen_t len) 3 { 4 char sendbuf[maxlen],recvbuf[maxlen]; 5 int n; 6 struct timeval tv; 7 tv.tv_sec=5;tv.tv_usec=0; 8 setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv)); //set 5 sec time out9 while((fgets(sendbuf,maxlen,fp))!=NULL) 10 { 11 sendto(sockfd,sendbuf,strlen(sendbuf),0,pserveraddr,len); 12 n=recvfrom(sockfd,recvbuf,maxlen,0,NULL,NULL); 13 if(n<0) 14 { 15 if(errno==EWOULDBLOCK) //time over but still have not recv from server.16 { 17 fprintf(stderr,"time out!\n"); 18 continue; 19 } 20 else //other error reason 21 { 22 perror("read error!\n"); 23 continue; 24 } 25 } 26 else 27 {28 recvbuf[n]=‘\0‘; 29 fputs(recvbuf,stdout); 30 } 31 32 } 33 }
使用了 setsockopt函數,本例僅使用了讀操作超時,若是想使用寫操作超時使用SO_SNDTIMEO選項。讀操作超時使用SO_RCVTIMEO.
使用SO_RCVTIMEO套接字選項為recvfrom設置超時