Search code examples
iosasyncsocketgcdasyncsocket

iOS: GCDAsyncSocket and its tag


In my app I'm using GCDAsyncSocket and I write and read in this way:

NSData *bufferWriteData = [NSData dataWithBytesNoCopy:bufferWrite length:17 freeWhenDone:YES];
[self.socket writeData:bufferWriteData withTimeout:-1 tag:1];
[self.socket readDataWithTimeout:-1 tag:1];

after I read in the delegate method the data:

- (void) socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{

    NSLog(@"did read data");

    if (tag == 1){

       //analyze my data...

       [self.socket readDataWithTimeout:-1 tag:1];
    }

inside this delegate method I recall the "readDataWithTimeout" so in this way I read all data.

The problem id when I do a new call, if I do:

[self.socket writeData:bufferWriteData withTimeout:-1 tag:2];
[self.socket readDataWithTimeout:-1 tag:2];

I start a new write and a new read with tag = 2; When the delegate method "didReadData" is called my code enter inside the block of tag = 1; it seems that it don't recognize the new tag.

Why it happen?


Solution

  • There are several ways to handle this. In your case, the best way probably just used a terminator to indicate the end of that data segment. You can read up there: TCP is a stream.

    NSData *MyCommandTerminator(void)
    {
        return [NSData dataWithBytes:"\x0D\x0A\x0B\x0A" length:4];
    }
    
    //callback from Asyncsocket for incoming data
    - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag  //sender and receiver
    {
        NSLog(@"GCDAsyncSocket didreaddata");
        // do what you wish with data and read again using a terminator
        [sock readDataToData:MyCommandTerminator() withTimeout:-1 tag:1];   //tag is not being used here
    }
    
    // your method to send data
    -(void)sendData:(NSData *)data
    {
            // NSData *bufferWriteData = [NSData dataWithBytesNoCopy:bufferWrite length:17 freeWhenDone:YES];
            NSLog(@"Sendata wehere _peerSocket is your instance of GCDAsyncSocket");
            NSMutableData *myData = [[NSMutableData alloc] initWithData:data];
            [myData appendData:MyCommandTerminator()];
            [_peerSocket writeData:myData withTimeout:-1 tag:2];   // tag is not being used here
        }