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



我有一个客户端程序,我需要send一个请求,并定时等待相应的response。但我应该收到所有其他响应,即使它是waiting or not

我的伪代码:

Recv部分:

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 requestn");
       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代码?如何解决这个问题?

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

Thanks in advance

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

最新更新