0

I am currently using CocoaAsyncSocket to send UDP Socket messages to a server. Occasionally I need to enforce that messages arrive in a specific order. Basically my code structure is similar to below.

NSMutableArray *msgs = @[@0, @1, @2].mutableCopy; 


-(void)sendMessages:(NSString *)str{
// blackbox function that converts to nsdata and sends to socket server
}

Normally, I don't care about the order so I am just blindly sending individual messages. For very specific commands this doesn't work. I have an example in java that spawns a new thread and sends the messages after a 0.2 second time span. I was hoping to find a more elegant solution in Objective-C. Does anybody have any suggestions for an approach?

Sean Dunford
  • 938
  • 1
  • 9
  • 24

1 Answers1

1

Guaranteeing a specific packet arrival order for UDP is exactly like doing the same for the postal system.

If you send two letters from country A to country B, there isn't really a way of telling which one will arrive first. Heck, one of them (or maybe even both) might even be lost and won't arrive at all. Sending the second letter 0.2 days after the first one increases the chances of "correct" ordering, but guarantees nothing.

The only way of maintaining order is adding sequence numbers to packets and buffering them on the receiving end. Then, once the relevant packets have arrived and have been ordered by sequence number you deliver them to processing. Note that this means that you'll also need a retransmission mechanism for lost packets, so if packets 1 and 3 arrive but 2 doesn't, the sender knows to send the missing packet before moving on. This is what TCP does.

Malt
  • 28,965
  • 9
  • 65
  • 105
  • I understand all of this and am less concerned with loss of packets than i am enforcing order. I have a delegate that provides Did send did receive did error. So I was more looking for an OBj-c mechanism that enables a queueing system that enforces sending one msg after the first has been received. – Sean Dunford Dec 29 '14 at 20:26