对于一个计算机网络项目,我们正在用 C++ 编写一个具有不同窗口协议(protocol)的 ftp 服务器。我们在实现工作超时功能时遇到问题。其要点是在传输数据包时设置时间戳,如果“ack”在一定时间内(例如 2.5 毫秒)没有恢复,则重新传输数据包。我们当前使用clock_gettime()
函数来获取当前时间和数据包时间戳。
这是我们遇到问题的 while 循环:
while(packet_sync_array[prev].recieved ==0 && t==0)
{
clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&timeout2);
currtime = timeout2.tv_nsec;
cout << "Is currtime: "<<currtime<< " - ptimeout " << ptimeout
<< " = " << (currtime - ptimeout) << " > "
<< (connection_parameters->timeoutInterval)*1000 << "?" << endl;
if((currtime - ptimeout)>((connection_parameters->timeoutInterval)*1000))
{
t = 1;
cout << "Prev PACKET TIMEDOUT" << endl;
cout << "Is currtime: "<<currtime<< " - ptimeout " << ptimeout
<< " = " << (currtime - ptimeout) << " > "
<< (connection_parameters->timeoutInterval)*1000 << "?" << endl;
}
}
其中,ptimeout
是发送数据包的时间,connection_parameters->timeoutInterval
是超时间隔。问题是,由于 ptimeout
是时间的长整数表示,有时它是一个非常大的值(例如 999715992)。这意味着它永远无法判断是否发生超时,因为在该值变得足够大之前,以纳秒为单位的当前时间将被重置为 0。
还有其他人用 C++ 处理过这些计时问题并有可能的解决方案吗?
谢谢!
编辑:
感谢您的快速回复!我能够弄清楚一些事情。修改 while 循环来检查超时+时间戳是否大于允许的长整数大小,让我看看在比较之前clock_gettime是否会回退到零。知道这一点后,我检查了当前时间是否>(超时间隔 - (最大长整型值 - 时间戳))。这允许最多 1 秒的超时,这对于解决此问题来说应该足够了。如果有人认为他们有更好的解决方案,请告诉我!谢谢! 这是感兴趣的人的代码:
if(((999999998-ptimeout)< (connection_parameters->timeoutInterval)*1000)&&(currtime - ptimeout)<0){
if(currtime > (((connection_parameters->timeoutInterval)*1000)-(999999998-ptimeout))){
t = 1;
cout << "this wrapped since " << currtime << " + " << (connection_parameters->timeoutInterval)*1000 << "is bigger than 999999999 and then timed out" << endl;
cout << "curr time " << currtime << "is bigger than" << endl;
cout << (connection_parameters->timeoutInterval)*1000 << endl;
cout << "-" << endl;
cout << (999999998-ptimeout) << endl;
cout << "---------------------------" << endl;
cout << (((connection_parameters->timeoutInterval)*1000)-(999999998-ptimeout)) << endl;
cout << "Prev PACKET TIMEDOUT" << endl;
cout << "Is currtime: "<<currtime<< " - ptimeout " << ptimeout << " = " << (currtime - ptimeout) << " > " << (connection_parameters->timeoutInterval)*1000 << "?" << endl;
}
}
else if((currtime - ptimeout)>((connection_parameters->timeoutInterval)*1000)){
t = 1;
cout << "Prev PACKET TIMEDOUT" << endl;
cout << "Is currtime: "<<currtime<< " - ptimeout " << ptimeout << " = " << (currtime - ptimeout) << " > " << (connection_parameters->timeoutInterval)*1000 << "?" << endl;
}
最佳答案
您可能想将代码更改为:
// time in microseconds
currtime = timeout2.tv_sec * 1000000 + timeout2.tv_nsec / 1000;
只要确保没有出现任何整数溢出即可!例如,显式转换为 64 位整数可能是个好主意。
此外,您很可能希望超时至少比 2.5 毫秒大一个数量级,甚至可能更多。例如,您在操作系统中的时间片很可能约为 17 毫秒,更不用说网络延迟了。
关于c++ - C++ 实现数据包超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5724718/