I am faced with a situation to maintain multiple timers in my socket communication program in C language. I have a client server program where both the client and the server ought to maintain a timer for every packet it send to the other machine. The protocol I am works like this- Every packet that machine A sends, machine B must acknowledge the same in a certain time. So a timer has to be there for every packet that machine A sends. If the timer senses timeout the socket connection must close. This way I need to maintain timers for each and every packet. The time for time-out is same for all the packets. I am looking to know if there is any provision in C to set different timers and distinguish among them to achieve the functionality above.
2 Answers
Instead of multiple timers, you can have one timer and a queue of "events". The queue is ordered by the time of the events. So when you send a packet, just add a disconnect-event to the event queue, and store some identifier to that event. If you receive a reply before the event fires, then remove the event from the queue.
I do not have a precise answer to what you are looking for, one of the ways you could do is create on either side (both at the client and the server) a pool of packets waiting for their ACKs, with each packet in the pool marked for its time-to-live.
Packets are then kicked out of the pool as soon as their ACK(s) are received. For packets that remain in the wait - the pool is watched by some keeper which could be clocked by a global Timer, and all the keeper does is decrements the TTL periodically for each packet in the pool (say every N ticks). Packets for which the ACK(s) did not come in time (TTL reached 0) are declared timed-out and sockets handled.