[英]window c++ : how to timeout receiveFrom function in a udp based conversation
我正在嘗試在UDP之上創建可靠的服務。 如果沒有數據包在指定的時間內到達,我在這里需要超時窗口c ++的receiveFrom
函數。 我在Java中執行DatagramSocket.setSoTimeout
但我不知道如何在Windows C ++中實現此目標。
謝謝
看一下setsockopt()
特別是SO_RCVTIMEO
。
嘗試使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.