【发布时间】:2011-01-29 05:48:19
【问题描述】:
我正在尝试在 UDP 之上创建可靠的服务。
在这里,如果没有数据包到达,我需要超时 receiveFrom 窗口 c++ 函数
在规定时间内。
在java中我这样做DatagramSocket.setSoTimeout但我不知道如何在windows c++中实现这一点。
谢谢
【问题讨论】:
我正在尝试在 UDP 之上创建可靠的服务。
在这里,如果没有数据包到达,我需要超时 receiveFrom 窗口 c++ 函数
在规定时间内。
在java中我这样做DatagramSocket.setSoTimeout但我不知道如何在windows c++中实现这一点。
谢谢
【问题讨论】:
尝试使用select。这将适用于 TCP 和 UDP 套接字。只是另一种方法来做与 Len 的回答相同的事情,但不是为套接字上的所有 recv 操作设置超时,您可以在逐个调用的基础上设置超时的长度。
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
int
input_timeout (int filedes, unsigned int seconds)
{
fd_set set;
struct timeval timeout;
/* Initialize the file descriptor set. */
FD_ZERO (&set);
FD_SET (filedes, &set);
/* Initialize the timeout data structure. */
timeout.tv_sec = seconds;
timeout.tv_usec = 0;
/* select returns 0 if timeout, 1 if input available, -1 if error. */
return TEMP_FAILURE_RETRY (select (FD_SETSIZE,
&set, NULL, NULL,
&timeout));
}
int
main (void)
{
fprintf (stderr, "select returned %d.\n",
input_timeout (STDIN_FILENO, 5));
return 0;
}
【讨论】:
看看setsockopt(),特别是SO_RCVTIMEO。
【讨论】: