Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c udp non-blocking socket with recvfrom and select

Tags:

c

sockets

udp

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


        }

}
like image 369
user3852803 Avatar asked Oct 20 '22 03:10

user3852803


1 Answers

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.

like image 128
Steffen Ullrich Avatar answered Nov 12 '22 21:11

Steffen Ullrich