首页 > 技术文章 > 使用SO_RCVTIMEO套接字选项为recvfrom设置超时

coversky 2017-11-19 15:53 原文

 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 out 
 9     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.

推荐阅读