Udjust UDP套接字数据接收等待时间。 [英] Udjust UDP socket data receive wait time.

查看:87
本文介绍了Udjust UDP套接字数据接收等待时间。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用VC ++开发UDP客户端服务器应用程序,我可以使用recvfrom读取数据



I am developing UDP client server application using VC++, I can read data using recvfrom

//this is a blocking call
	        if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1)	        {
	            die("recvfrom()");
	        }





如何减少无限等待数据到固定的几秒钟?



How I can reduce this infinite waiting for a data to a fixed seconds of time ?

推荐答案

除非你真的需要,否则不要使用线程。

你有几种选择。

我建议使用select()或poll()函数。

select()也出现在windows套接字API中,其语法类似于BSD API。

所以这个可能是在简单的情况下最通用。

Don''t use the threads unless you really have to.
You have a several alternatives.
I suggest to use select() or poll() functions.
select() also appears in windows sockets API and has a syntax similar to BSD API.
So this one could be the most universal in simple cases.
struct fd_set fds = { 0 }; // will be checked for being ready to read
FD_ZERO(&fds);
FD_SET(s, &fds);

// sets timeout
struct timeval tv = { 0 };
tv.tv_sec = TIMEOUT;
tv.tv_usec = 0;

int ret = select( s + 1, &fds, NULL, NULL, &tv );
if (  ret < 0 )
{
    // error on select()
}
else if ( ret == 0 )
{
    // timeout
    // possible function return or loop breakage
}
else if ( FD_ISSET( s, &fds ) ) // data to read?
{

    //this is a blocking call
    if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1)
    {
        die("recvfrom()");
    }

}



但是,也许你可能想重新设计一个类似recvfrom的函数应用。使用非阻塞API或在主循环中使用select()/ poll()或smth else

(做研究,有多种选择)。



在UNIX / Linux上你也可以使用SIGALRM例如:


But maybe, instead of writing a recvfrom-like function with time-out you may want to redesign the application. Use non-blocking API or use select()/poll() or smth else in the main loop
(do research, there are multiple choices).

On UNIX/Linux you can use also SIGALRM eg.:

signal(SIGALRM, sig_alrm);
alarm(TIMEOUT);
if ( recvfrom( ... ) < 0 )
    if ( errno == EINTR )
        // timed out
    else
       // other error
else
  // no error
  alarm(0);



请参阅手册了解不同的功能。

希望它能帮到你!

问候!



PS

我忽略了你正在使用VC ++。基于select()的解决方案工作正常。

你宁愿不发现alarm()和sigaction()有用。在Windows中,有WaitForMultipleObjects或IO Completion Ports用于创建高性能服务器。

这是一个非常有趣的问题。如果你想写一个专业的服务器软件,我鼓励你探讨这个话题。

快速搜索,我发现,例如,这篇文章:

IP组播 - 使用I / O完成端口与UDP [ ^ ]


这篇关于Udjust UDP套接字数据接收等待时间。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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