1、设置阻塞接收以及超时时间
//设置阻塞
int flags = fcntl(sock, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags & ~O_NONBLOCK);
//设置接收超时时间
int timeout_ms=500;//毫米
struct timeval timeout;
timeout.tv_sec = timeout_ms/1000;//秒
timeout.tv_usec = (timeout_ms%1000)*1000;//微秒
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) < 0) {
perror("setsockopt SO_RCVTIMEO failed:");
printf("setsockopt SO_RCVTIMEO failed,timeout_ms=%d\n",timeout_ms);
return -1;
}
//把SO_RCVTIMEO换成SO_SNDTIMEO就是发送超时
2、设置不阻塞接收
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);