socket编程中的超时设置示例详解之二

操作(send, recv)超时
对它们有两种方式来设置超时,
1. 将send, recv设置成非阻塞模式,然后用select来设置超时机制,就如上面的connect方式一样。
2. 使用setsockopt()函数来设置相应的超时机制。
因为前一种方式在connect中重点说明,本节来主要说明第二种方式。
示例代码如下:
对send和recv进行了超时设置,并最多做四次重试

/* * \brief * tcp client */
define TIMEOUT_TIME 2
define SERVPORT 8080
define MAXDATASIZE 100

int main(int argc, char *argv[])
{
  int sockfd, recvbytes;
  char rcv_buf[MAXDATASIZE]; /*./client 127.0.0.1 hello */
  char snd_buf[MAXDATASIZE];
  struct hostent *host;             /* struct hostent * { * char *h_name; // general hostname * char **h_aliases; // hostname's alias * int h_addrtype; // AF_INET * int h_length; * char **h_addr_list; * }; */
  struct sockaddr_in server_addr;


  /* Timeout */
  struct timeval timeout;
  socklen_t len = sizeof(timeout);
  int result;
  int error;
  int i;


  if (argc < 3)
  {
    printf("Usage:%s [ip address] [any string]\n", argv[0]);
    return 1;
  }


  *snd_buf = '\0';
  strcat(snd_buf, argv[2]);


  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  {
    perror("socket:");
    exit(1);
  }


  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(SERVPORT);
  inet_pton(AF_INET, argv[1], &server_addr.sin_addr);
  memset(&(server_addr.sin_zero), 0, 8);


  /* create the connection by socket * means that connect "sockfd" to "server_addr" */
  if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)
  {
    perror("connect");
    exit(1);
  }


  /* send 超时设置,并最多做四次重试 */
  timeout.tv_sec = TIMEOUT_TIME;
  timeout.tv_usec= 0;
  result = setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout.tv_sec, len);
  if (result < 0)
  {
    perror("setsockopt:");
    exit(1);
  }


  for(i = 0; i < 4; i++)
  {
    if (send(sockfd, snd_buf, sizeof(snd_buf), 0) == -1)
    {
      getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len);
      if (error == 0)
      {
        printf("recv timeout!\n");
        continue;
      }
    }
    else
    {
      break;
    }
  }
  printf("send:%s\n", snd_buf);




  /* recv 超时设置,并最多做四次重试 */
  timeout.tv_sec = TIMEOUT_TIME;
  timeout.tv_usec= 0;
  result = setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout.tv_sec, len);
  if (result < 0)
  {
    perror("setsockopt:");
    exit(1);
  }
  for(i = 0; i < 4; i++)
  {
    if ((recvbytes = recv(sockfd, rcv_buf, MAXDATASIZE, 0)) == -1)
    {
      getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len);
      if (error == 0)
      {
        printf("recv timeout!\n");
        continue;
      }
    }
    else
    {
      break;
    }
  }
  rcv_buf[recvbytes] = '\0';
  printf("recv:%s\n", rcv_buf);
  close(sockfd);
  return 0;
}

你可能感兴趣的:(socket,select)