çUDP无阻塞recvfrom的选择插座 [英] c udp non-blocking socket with recvfrom and select

查看:210
本文介绍了çUDP无阻塞recvfrom的选择插座的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在有选择功能的客户端的非阻塞套接字实现。但随着预期这是行不通的。在code低于它从来没有运行到别人,RV始终为1,当没有什么是对插座应用程序停止了一会儿,继续当另一个消息是在插座上。我不希望这样的行为,我想客户端发回的信息到服务器时,没有什么插座给recvfrom上。

  FD_SET readfds;的fcntl(SD,F_SETFL,O_NONBLOCK);
而(1){        FD_ZERO(安培; readfds);
        FD_SET(SD,&安培; readfds);        RV =选​​择(SD + 1,&安培; readfds,NULL,NULL,NULL);        如果(RV == 1){            为nbytes = recvfrom的(SD,BUF,RW_SIZE,0,(结构sockaddr *)及srv_addr,&安培; addrlen中);
        }其他{            的printf(我从来没有在这里,所以我不能发送消息到服务器\\ n!);
        }}

与timeval结构:

  FD_SET readfds;
的fcntl(SD,F_SETFL,O_NONBLOCK);
timeval结构电视;
而(1){        FD_ZERO(安培; readfds);
        FD_SET(SD,&安培; readfds);        tv.tv_sec = 0;
        tv.tv_usec = 0;        RV =选​​择(SD + 1,&安培; readfds,NULL,NULL,&安培;电视);        如果(RV == 1){            为nbytes = recvfrom的(SD,BUF,RW_SIZE,0,(结构sockaddr *)及srv_addr,&安培; addrlen中);
        }其他{            的printf(我一直在这里像现在\\ n!);
        }}


解决方案

您设置超时(选择的最后一个参数)为NULL,这意味着它只会返回一次数据可用的插座上(或中断)。您需要设置超时应该等待。超时可能是0,如果你不想等待,但0是指使用 timeval结构* tv_sec = 0 tv_usec = 0 而不是使用 timeval结构* 像你这样。

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


        }

}

解决方案

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.

这篇关于çUDP无阻塞recvfrom的选择插座的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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