Question

I'm wondering how to use the tag parameter in methods such as

readDataWithTimeout: tag:
writeData: tag:

What happens if I want to use the tag to identify the type of packet ? For example is I say tag == 2 means that the packet is a message from a client, tag == 1 means that the packet is a message from the server ... If this is ok do I need to call readData: withTag: several times (once for each different tag) ?

[readDataWithTimeout:-1 tag:1];
[readDataWithTimeout:-1 tag:2];

Is there a way to say: "read every data without caring about the tag", and then in the didReadData: withTag: method handle the data according to the tag ?

Was it helpful?

Solution

I think you're slightly misunderstanding the tag concept. The read operations aren't saying "Read data that has been tagged as 2". They are saying "Read the next data off the wire, and tag it as 2 for future reference."

The tag is never sent over the wire - the server didn't tag the data and send it to the client to read. It's a completely optional concept only used to distinguish local operations from each other. In other words, The data being read has no tag. The tag is something you assign to the read operation, so you can identify it later once it's complete.

For example, say you're reading data as a series of headers and payloads. You could use the tag to distinguish a header read from a payload read:

const NSInteger kHeaderTag = 1;
const NSInteger kPayloadTag = 2;

// Assume you know to expect a header, so tag the read operation as such.
[self readDataWithTimeout:-1 tag:kHeaderTag];

// Next assume you know to expect a payload, so tag the read operation as such.
[self readDataWithTimeout:-1 tag:kPayloadTag];

Then you can identify it later...

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    if (tag == kHeaderTag)
    {
        // Handle header
    }
    else if (tag == kPayloadTag)
    {
        // Handle payload
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top