title: How to separate data packets when using GCDASyncSocket
body: <p>Can anyone help me? I intensively exchange data between two devices over TCP protocol by using  GCDAsyncSocket. I send data like this:</p>
  
  <pre><code>     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];
  }
  </code></pre>
  
  <p>I read data like this:</p>
  
  <pre><code>- (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];
  }
  </code></pre>
  
  <p>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 <code>NSKeyedUnarchiver</code> throws exception <code>Incomprehensible archive</code>. </p>
  
  <p>As far as i understand i should separate the packets somehow. What i tried was appending separatory symbols to the data being sent:</p>
  
  <pre><code>[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
  </code></pre>
  
  <p>and trying to read it like this:</p>
  
  <pre><code>[socket readDataToData:[GCDAsyncSocket CRLFData] timeout:-1 tag:some_tag];
  </code></pre>
  
  <p>But it didn't help. What am i doing wrong and what should i do instead?</p>