用C超时实施TFTP [英] Timeout implementation in C for TFTP
问题描述
我想实现我的C实现TFTP的超时机制,我找一些一般帮助。
I am trying to implement the the timeout mechanism in my c implementation of TFTP, and i am looking for some general help.
我想知道是如何管理超时的情况。我使用了premature超时机制与信号/报警功能,但不知何故,我被困在如何处理我的超时,即如果数据包(ACK或数据)失手发生超时怎么送回来previous包或应答至服务器。
What I am wondering is how to manage the timeout situation. The premature timeout mechanism that I used is with signal/alarm functions, but somehow I am stuck in how to handle my timeouts, that is if the packet (ack or data) is missed and a timeout occurs how to send back the previous packet or ack to the server.
推荐答案
避免信号和报警如果可能的话。
Avoid signal and alarm if possible.
要么使用<一个href=\"http://forums.$c$cguru.com/showthread.php?353217-example-of-SO_RCVTIMEO-using-setsockopt%28%29\"相对=nofollow> SO_RCVTIMEO 套接字选项或只使用有选择 T秒超时。
Either use SO_RCVTIMEO socket option or just use select with a timeout of T seconds.
如果选择()调用返回,你的插口是不是在读集,或者如果与超时错误recvfrom的回报,那么你可以采取适当的行动,你的code。
If the select() call returns and your socket is not in the read set, or if recvfrom returns with a timeout error, then you can take appropriately action in your code.
超时使用示例:
timeval tv = {0,0};
tv.tv_sec = 5;
socklen_t optionlength = sizeof(tv);
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, optionlength);
while (1)
{
result = recvfrom(s, buffer, bufferlength, 0);
if (result == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)) )
{
// handle timeout
}
else if (result == -1)
{
// handle critical error
}
else
{
// process next packet
}
}
选择使用示例:
while (1)
{
timeval tv = {0,0};
tv.tv_sec = 5;
fd_set readset = {};
FD_ZERO(&readset);
FD_SET(s, &readset);
select(s+1, &readset, NULL, NULL, &tv);
if (FD_ISSET(s, &readset))
{
result = recvfrom(s, buffer, bufferlength, 0);
if (result == -1)
{
// handle error
}
else
{
// process packet
}
}
else
{
// handle timeout
}
}
这篇关于用C超时实施TFTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!