简体   繁体   English

使 recvfrom() 函数非阻塞

[英]Making recvfrom() function non-blocking

I am working on a UDP server/client application.我正在开发 UDP 服务器/客户端应用程序。

For finding out if any of the client is down, the server sends a handshake message to the client.为了查明是否有任何客户端宕机,服务器会向客户端发送握手消息。 Then, the server waits for the response of client to send some data to assure that the client is active.然后,服务器等待客户端的响应发送一些数据以确保客户端处于活动状态。 For this the server blocks in call to recvfrom() unless the client replies back, but if the client is down, the server blocks infinitely in call to recvfrom() .为此,除非客户端回复,否则服务器会阻止对recvfrom()调用,但如果客户端关闭,则服务器会无限地阻止对recvfrom()调用。

I want to implement such a functionality on my server so that it waits in the call to recvfrom() for a specific time (say 2 secs).我想在我的服务器上实现这样的功能,以便它在对recvfrom()的调用中等待特定时间(比如 2 秒)。 If no data was received from the client within 2 seconds, the client is considered to be dead and recvfrom() returns.如果在 2 秒内没有从客户端接收到数据,则认为客户端已死并且recvfrom()返回。

Is there any way to do it?有什么办法吗? I searched internet but found solutions like setting MSG_DONTWAIT flag that returns immediately when no data received, but in my case, I don't want recvfrom() to return immediately but wait for data for a specific duration of time, and when no data received for that specific duration, the recvfrom() function should return.我搜索了互联网,但找到了解决方案,例如设置MSG_DONTWAIT标志,该标志在未收到数据时立即返回,但在我的情况下,我不希望recvfrom()立即返回,而是在特定的时间段内等待数据,并且在未收到数据时在那个特定的持续时间内, recvfrom()函数应该返回。

The easiest way would be to use setsockopt() to set a receive time-out for the socket in question.最简单的方法是使用setsockopt()为相关套接字设置接收超时。

SO_RCVTIMEO is used for this. SO_RCVTIMEO用于此目的。

If a time-out has been set for a socket passed to recvfrom() , the function returns after this time-out if no data had been received.如果为传递给recvfrom()的套接字设置了超时,则该函数在此超时后返回,如果没有收到数据。

For instance, to set a 10 μs read time-out (add error-checking on the value returned by setsockopt() as necessary):例如,要设置 10 μs 读取超时(根据需要对setsockopt()返回的值添加错误检查):

#include <sys/types.h> 
#include <sys/socket.h>

...

struct timeval read_timeout;
read_timeout.tv_sec = 0;
read_timeout.tv_usec = 10;
setsockopt(socketfd, SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof read_timeout);

For details on Windows please see here , and on Linux see here and/or here (POSIX) .有关Windows 的详细信息,请参阅此处在 Linux 上,请参阅此处和/或此处 (POSIX)

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

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