c udp 非阻塞套接字,带有 recvfrom 和 select [英] c udp non-blocking socket with recvfrom and select

查看:21
本文介绍了c udp 非阻塞套接字,带有 recvfrom 和 select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在客户端实现带有选择功能的非阻塞套接字.但它没有按预期工作.在下面的代码中,它永远不会遇到 else , rv 始终为 1 并且当套接字上没有任何内容时,应用程序会停止一段时间,并在套接字上有其他消息时继续.我不希望这种行为,我希望客户端在套接字上没有任何内容可接收时将消息发送回服务器.

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


        }

}

使用 struct timeval:

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


        }

}

推荐答案

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

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.

这篇关于c udp 非阻塞套接字,带有 recvfrom 和 select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆