zoukankan      html  css  js  c++  java
  • 使用SO_RCVTIMEO套接字选项为recvfrom设置超时

     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!
    ");
    18                 continue;
    19             }
    20             else    //other error reason
    21             {
    22                 perror("read error!
    ");
    23                 continue;
    24             }
    25         }
    26         else
    27         {
    28             recvbuf[n]='';
    29             fputs(recvbuf,stdout);
    30         }
    31         
    32     }
    33 } 

    使用了 setsockopt函数,本例仅使用了读操作超时,若是想使用写操作超时使用SO_SNDTIMEO选项。读操作超时使用SO_RCVTIMEO.

  • 相关阅读:
    python 笔记8
    python笔记6
    python笔记5
    python笔记4
    python笔记3
    python课程2
    cobbler 坑爹指南
    hadoop filesystem 删除文件 复制文件 重命名文件
    hadoop 文件 复制 移动 FileUtil.copy
    soinn
  • 原文地址:https://www.cnblogs.com/coversky/p/7859971.html
Copyright © 2011-2022 走看看