简体   繁体   English

如何在C UDP套接字程序中配置重传超时?

[英]How do I configure a retransmit timeout in a C UDP socket program?

I have a simple UDP socket program in C. The client transmits data to the server and receives acknowledgements. 我在C语言中有一个简单的UDP套接字程序。客户端将数据传输到服务器并接收确认。 I already know how to configure a timeout so that if 'recvfrom()' doesn't receive anything in a certain period of time the alarm goes off. 我已经知道如何配置超时,这样,如果'recvfrom()'在特定时间内没有收到任何警报,便会响起。

HOWEVER, there are a few more situations I need to handle. 但是,我还需要处理其他几种情况。 What if I receive a reply from an unexpected address, or the reply is not formatted correctly? 如果我收到来自意外地址的答复,或者答复的格式不正确怎么办? I don't want to retransmit immediately, only when the alarm goes off. 我不希望仅在警报响起时立即重新发送。

Let me know if I need to clarify. 让我知道是否需要澄清。

Look into select(2) and poll(2) - you can wait on a socket for a specified amount of time. 查看select(2)poll(2) -您可以在套接字上等待指定的时间。 You can then restart the wait with lesser timeout if you need. 然后,可以根据需要以更短的超时时间重新开始等待。

If you are on linux, look into epoll(7) and timerfd_create(2) . 如果您使用的是Linux,请查看epoll(7)timerfd_create(2)

You are going to have to do processing on the received datagrams if you want to check and see if they are from an unexpected address or if they are formatted incorrectly. 如果要检查接收的数据报,并查看它们是否来自意外的地址或格式是否错误,则必须对其进行处理。 To make handing these cases easier you should build a state machine that handles your different cases. 为了使处理这些案件更加容易,您应该构建一个处理不同案件的状态机。

For example you could have the following states: 例如,您可能具有以下状态:

  • read timeout 读取超时
  • data format error 数据格式错误
  • invalid transmit address 无效的发送地址
  • valid data 有效数据

Also if you detect one of these other error conditions and you don't want to immediately retransmit you will need you some sort of timer or sleep condition to wait until you are ready to retransmit. 同样,如果您检测到这些其他错误情况之一,并且不想立即重传,则将需要某种计时器或睡眠条件来等待,直到准备好重传为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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