Вы также можете использовать Threads для этой цели, что довольно просто и требует меньше строк кодов.
Вам просто нужно создать и определить эту функцию:
unsigned long CALLBACK packetTimer(void *pn){
//This is our Packet Timer
//It's going to run on a Tread
//If ack[thisPacketNumber] is not true
//We gonna check will check for packet time
//If it's reached to its limit we gonna send this packet again
//and reset the timer
//If ack[] becomes true
//break the while loop and this will end this tread
int pno = (int)pn;
std::clock_t start;
double duration;
start = std::clock();
while(1){
if(!ack[pno]){
duration = (std::clock() - start)/(double) CLOCKS_PER_SEC;
if(duration > 0.5){
//This tells that we haven't received our ACk yet for this packet
//So send it again
printf("SendBuffer for Packet %d: %s", pno, packets[pno]->data);
//Resending packet again
send_unreliably(s,packets[pno]->data,(result->ai_addr));
//Reseting the timer
start = std::clock();
}
}else{break;}
}
}
И внутри вашего цикла в то время, когда вы посылать и принимать пакеты на приемник, вы просто определить:
unsigned long tid;//This should be outside the while loop,
//Ideally in the beginning of main function
CreateThread(NULL,0,packetTimer,(void *)packetNumber,0,&tid);
Это implementaion является для окон, для UNIX нам нужно использовать pthread()
Это все. И не забывайте добавлять необходимые заголовочные файлы, такие как:
#include <stdlib.h>
#include <cstdio>
#include <ctime>