Search code examples
iosobjective-ciphonedelaymultipeer-connectivity

IOS / MultipeerConnectivity / Delay between SendData and ReceiveData


Im having a game that sends a Players position.x, position.y and angle in an mutablearray every 0.05 seconds using Multipeer senddata.

NSMutableArray *Messagee = [[NSMutableArray alloc] initWithCapacity:10];
[Messagee addObject:x];
[Messagee addObject:y];
[Messagee addObject:ang];


NSData* Message = [NSKeyedArchiver archivedDataWithRootObject:Messagee];
dispatch_async(dispatch_get_main_queue(), ^(void) {  
[self.partyTime sendData:Message
                withMode:MCSessionSendDataUnreliable
                   error:nil];      
});

The other player gets the data using

- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID;

The problem I face is that the didrecievedata get called very unregulary, as it should be called every 0.05 seconds (i send data every 0.05 seconds).

I experience huge differences in delay going up to 0.20 seconds between two didrecieve data, followed by 0.00001 seconds for the next packet.

I need a constant didrecievedata of 0.05 seconds equal the senddata from the other player to synchronize the players positions.

Is there any way to have a very little delay between the senddata and recievedata? Equal the Ping for example?

Is my data that I send (NSMutablearray) to big -> delay

Should i be using Streams ?

Thanks a lot!


Solution

  • Anything sent over an open network will experience irregular delays, depending on how busy the network is, and how much interference there is. That is something you simply will need to deal with.

    There are normally two approaches that you can use to deal with that, pick the one that is most applicable to your application:

    1. Put a timestamp in the message and let the receiving side handle them directly, but use the timestamp to know when each message was supposed to be used, adjusting your logic to that.
    2. Introduce a fixed delay at the receiving side, roughly equal to the longest expected delay. Then queue the received messages, and forward them to the rest of the application at the regular rate.

    In either case, you need to be prepare for dropped messages as well.