繁体   English   中英

Windows C ++:如何在基于udp的对话中使receiveFrom函数超时

[英]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.

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