如何在 c 套接字中使用 select 等待特定响应而不忽略其他响应?

问题描述 投票:0回答:1

我有一个客户端程序,我需要

send
请求并定时等待相应的
response
。但我应该收到所有其他回复,即使是
waiting or not

我的伪代码:

接收部分:

struct timeval timeout = {
     .tv_sec = 5,
     .tv_usec = 0
};

while (1) {
   ret = select(maxfd + 1, &rdfd, NULL, NULL, &timeout);
   if (ret == 0) {
       fprintf(stderr, "No response for request\n");
       return;
   }

   ret = recvfrom(.buf..);

   struct standard_msg *std_msg = buf;

   switch(std_msg->type) {
        case TYPE_1: 
            if expecting response for TYPE_1
            read and retun from here;
            else loop until timeout
        case TYPE_2:
            if expecting response for TYPE_2
            read and return from here
            else loop until timeout
        default:
            print buf
   }
}

发送部分:

while(1) {
   struct timeval timeout = {
      .tv_sec = 50,
      .tv_usec = 0
   }
   select(1, NULL, NULL, NULL, &timeout);
   send_a_packet_wait_for_ITS_response(); //which will call the recv_secion
}

send
是通过每
50
秒读取文件内容而发生的。假设发送的数据包立即得到回复,现在我将等待
50
秒发送其他数据包。在此期间,我无法
read
收到任何数据包。如果文件到达
EOF
则没有任何内容可发送,现在我也无法
read
任何数据包。

所以这里我需要连续监听所有数据包,也监听特定的数据包。是否可以为所有其他数据包运行

listen
代码,并为特定数据包运行
listen
代码?我该如何解决这个问题?

我的目的是在配置的超时内获得特定请求的回复,而不丢失其他数据包。

提前致谢

c sockets posix-select
1个回答
-1
投票

当您从套接字读取数据时,操作系统不会对有效负载本身(即 OSI 第 5..7 层)进行解释。这意味着像这样的所有应用程序层逻辑都必须在应用程序本身中完成。这意味着即使您不需要知道每个数据包,您也需要读取它,在这种情况下,您可以将其放入某个应用程序特定的缓冲区中以供以后使用。

© www.soinside.com 2019 - 2024. All rights reserved.