简体   繁体   English

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

[英]c udp non-blocking socket with recvfrom and select

I want to implement at the client side non-blocking socket with select function. 我想在客户端实现具有select函数的非阻塞套接字。 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. 在下面的代码中,它永远不会运行到else,rv始终为1,当没有任何内容时,套接字应用程序停止一段时间,并在套接字上有另一条消息时继续。 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: 使用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");


        }

}

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). 您将超时(select的最后一个参数)设置为NULL,这意味着它只会在套接字(或中断)上的数据可用时返回。 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. 如果你不想等待超时可能是0,但是0意味着使用struct timeval* with tv_sec=0tv_usec=0并且不像你那样使用struct timeval* NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM