Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8335403
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T03:40:05+00:00 2026-06-09T03:40:05+00:00

Can anyone help me? I intensively exchange data between two devices over TCP protocol

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T03:40:07+00:00Added an answer on June 9, 2026 at 3:40 am

    I guess, you misunderstood the role of the tag. GCDAsyncSocketis (as the name suggests) an asynchrone socket. The tag helps you to match the received data with the receive order and the send succes with the send order, resp.

    E.g., if you want to send data, you use writeData:messageA withTimeout:-1 tag: tagA (or something similar) to give your socket the order to send somewhen in the near future. It won’t be necessarily right now. And you can immediately give the next order to send another message, say messageB with tag tagB.
    To know, that the messageA was really sent, you get the notification via socket:aSocket didWriteDataWithTag:aTag. Here, aTaghas the value of tagA if messageAwas sent, and the value of tagB if messageB was sent. The tag is not sent with the message; it only helps you to identify your order.

    It is the very same thing at the receiving side. You give the order to receive (somewhen) some data and assign a tag to that very order. Once you did receive data, the notification (via socket:didReadData:withTag:) shows you the tag to let you know, which order succeed.

    You may use the tag for some semantic information and put it in your message. But even then, the tag in the notification is the tag of the receive order, but never the one of the send order. If you want to use the tag you put in the message at the receiving side, you have to receive (at least parts of) the message first and parse it.

    To come to the core of your issue: You have basically two possibilities to know, which kind of data is arriving:

    1. Know the sequence of sent data and receive it in the very same order.
    2. Use a message head that identifies the kind of data. Receive only the head and receive and parse the remains of your message in dependence of the head data.

    EDIT

    Here is an example for the 2nd approach. Assume you can sent a number of object of classes A, B, etc. Your header could include type and size of your data:

          typedef struct {
                NSUInteger type_id;
                NSUInteger size;
          } header_t;
    
          #define typeIdA   1
          #define typeIdB   2
          // ...
    

    Once you want to send an object obj with objKey:

         NSMutableData *data = [NSMutableData data];
         NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
         [archiver encodeObject:obj forKey: objKey];
    
         header_t head;
         if ([obj class] == [A class]) {
            head.type_id = typeIdA;
         } else if ([obj class] == [B class]) {
            head.type_id = typeIdB;
         } else ...
    
         // ....
    
         header.size = data.lengh;
         NSData* headData = [NSData dataWithBytes: &header length: sizeof(header)];
    
         dataWithBytes:length:
         header = NSData.length;
         [asyncSocket writeData:headData withTimeout:-1 tag:headTag];
         [asyncSocket writeData:data withTimeout:-1 tag:dataTag];
    

    If you want, you can get notifications on successful sending or errors, but I skip this here.
    At receiver side, you expect a header first:

        [receiveSocket readDataToLength:sizeof(header_t) withTimeout:-1 tag:rcvHdrTag];
        // rcvHdrTag must not match one of the typeIdX tags
    

    In your socket:didReadData:withTag: you have to distinguish, if you get the header or the remains (the receiving of the remains is initiated here!)

       - (void)socket:(GCDAsyncSocket *)aSocket didReadData:(NSData *)data withTag:(long)tag {
            header_t head;
            id obj;
            id key;
    
           switch (tag) {
               case rcvHdrTag:
                   [data getBytes:&head length:sizeof(header)];
                   // now you know what to receive
                   [aSocket readDataToLength:header.size withTimeout:-1 tag:header.type];
                   return;
                   break; // I know, redundancy :-)
              case typeIdA:
                   objKey = objKeyA;   // whatever it is...
                   break;
              case typeIdB:
                   objKey = objKeyB;   
                   // ....
           }
           NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
           obj = [unarchiver decodeObjectForKey:objKey];
    
           // store your object ...
       }
    

    This is not the most elegant example, and it ignores object trees and inter-object dependencies in archives, but you should get the idea.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can anyone help me how to run two Java codes parallely using processes (not
Can anyone help me to create a simple viewing of cam using just a
Can anyone help me on how could I join two tables without merging the
Can anyone help me with the script which will delete the data older than
Can anyone help explain this? I am using the Populator and Faker gems to
can anyone help me how to display a simple timer using TTimer component in
Can anyone help - this is driving me mad. I am calling a mysql
Can Anyone help me why x2 prints zero. I guess because of floating point
Can anyone help me how to split /explode verse format to 3 parts? The
Can anyone help me to get good WordPress interview questions and answers. Any link

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.