【问题标题】:window c++ : how to timeout receiveFrom function in a udp based conversationwindow c++:如何在基于 udp 的对话中使 receiveFrom 函数超时
【发布时间】:2011-01-29 05:48:19
【问题描述】:

我正在尝试在 UDP 之上创建可靠的服务。 在这里,如果没有数据包到达,我需要超时 receiveFrom 窗口 c++ 函数 在规定时间内。 在java中我这样做DatagramSocket.setSoTimeout但我不知道如何在windows c++中实现这一点。

谢谢

【问题讨论】:

    标签: c++ windows timeout udp


    【解决方案1】:

    尝试使用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;
     }
    

    【讨论】:

      【解决方案2】:

      看看setsockopt(),特别是SO_RCVTIMEO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-23
        • 2014-02-08
        • 2015-10-31
        • 1970-01-01
        • 2020-07-12
        • 1970-01-01
        • 2017-06-08
        • 2021-04-28
        相关资源
        最近更新 更多