I want to implement at the client side non-blocking socket with select function. But it doesn't work as expected. In the code below it never runs into else , rv is always 1 and when nothing is on the socket application stops for a while and continue when another messages is on the socket. I don't want that behavior , I want that client sends back message to the server when there is nothing on the socket to recvfrom.
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");
}
}
with 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");
}
}