c udp non-blocking socket with recvfrom and select

32,950

You set the timeout (last parameter of select) to NULL, which means it will only return once data are available on the socket (or interrupt). You need to set a timeout it should wait. The timeout might be 0 if you don't want to wait, but 0 means to use a struct timeval* with tv_sec=0 and tv_usec=0 and not use a struct timeval* of NULL like you did.

Share:
32,950
user3852803
Author by

user3852803

Updated on July 09, 2022

Comments

  • user3852803
    user3852803 almost 2 years

    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");
    
    
            }
    
    }