c udp带有recvfrom和select的非阻塞套接字

我想在客户端实现具有select函数的非阻塞套接字。 但它没有按预期工作。 在下面的代码中,它永远不会运行到else,rv始终为1,当没有任何内容时,套接字应用程序停止一段时间,并在套接字上有另一条消息时继续。 我不希望这种行为,我希望当socket上没有任何东西要重新发送时,客户端会将消息发送回服务器。

fd_set readfds; fcntl(sd, F_SETFL, O_NONBLOCK); while (1) { FD_ZERO(&readfds); FD_SET(sd, &readfds); rv = select(sd + 1, &readfds, NULL, NULL, NULL); if(rv == 1){ nbytes = recvfrom(sd, buf, RW_SIZE, 0, (struct sockaddr *) &srv_addr, &addrlen); } else { printf("I'm never here so I can't send message back to the server!\n"); } } 

使用struct timeval:

 fd_set readfds; fcntl(sd, F_SETFL, O_NONBLOCK); struct timeval tv; while (1) { FD_ZERO(&readfds); FD_SET(sd, &readfds); tv.tv_sec = 0; tv.tv_usec = 0; rv = select(sd + 1, &readfds, NULL, NULL, &tv); if(rv == 1){ nbytes = recvfrom(sd, buf, RW_SIZE, 0, (struct sockaddr *) &srv_addr, &addrlen); } else { printf("I'm always here like now ! \n"); } } 

您将超时(select的最后一个参数)设置为NULL,这意味着它只会在套接字(或中断)上的数据可用时返回。 你需要设置它应该等待的超时。 如果您不想等待超时可能为0,但0表示使用带有tv_sec=0tv_usec=0struct timeval* ,并且不像您那样使用struct timeval*时间值struct timeval* NULL。