Can anyone help me? I intensively exchange data between two devices over TCP protocol by using GCDAsyncSocket. I send data like this:
NSMutableDictionary *packet = [[[NSMutableDictionary alloc] init] autorelease];
[packet setObject:[NSNumber numberWithInt:MultiPlayerTypeInfoNextRoundConfirm] forKey:@"type_info"];
[packet setObject:[NSNumber numberWithBool:YES] forKey:@"connection_confirmation"];
NSMutableData *data = [[NSMutableData alloc] initWithData:[NSKeyedArchiver archivedDataWithRootObject:packet]]; //[NSKeyedArchiver archivedDataWithRootObject:packet];
if (currentGameMode == GameModeServer)
[(ServerMultiplayerManager *)multiplayerManager sendNetworkPacket:data withTag:MultiPlayerTypeInfoNextRoundConfirm];
- (void)sendNetworkPacket:(NSData *)data withTag:(long)tag
{
[asyncSocket writeData:data withTimeout:-1 tag:tag];
}
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
NSLog(@"DID WRITE DATA tag is %ld", tag);
[sock readDataWithTimeout:-1 tag:0];
}
I read data like this:
- (void)socket:(GCDAsyncSocket *)sender didReadData:(NSData *)data withTag:(long)tag
{
NSString *receivedInfo = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
[info_data setData:data];
NSLog(@"DID READ DATA WITH TAG %ld", tag);
if ([receivedInfo isEqualToString:ROOM_FILLED])
{
isMaster = (tcpRequest.identifier == MASTER_CHAR);
NSLog(@"IS MASTER SET %d", isMaster);
[multiplayerDelegate setGameModeServer];
[multiplayerDelegate startGame];
}
else
[self dataProcessing:info_data];
[sender readDataWithTimeout:-1 tag:0];
}
- (void)dataProcessing:(NSData *)data
{
NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
MultiPlayerTypeInfo typeInfo = [[dict objectForKey:@"type_info"] intValue];
}
My issue that these packets of data get messed. Say a packet marked with tag 10 is read at the receiver device as packet marked with tag 11, which was sent immediately after packet 10, and when it comes to unarchiving of actual packet 11 NSKeyedUnarchiver
throws exception Incomprehensible archive
.
As far as i understand i should separate the packets somehow. What i tried was appending separatory symbols to the data being sent:
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
and trying to read it like this:
[socket readDataToData:[GCDAsyncSocket CRLFData] timeout:-1 tag:some_tag];
But it didn't help. What am i doing wrong and what should i do instead?