Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is GCDAsyncSocket readData designed to read only once?

One thing I found unintuitive about GCDAsyncSocket's didReadData callback is that it doesn't get call again unless you issue another readData. Why is it designed this way? Is it correct to expect the user of the library to initiate another read call in order to get a callback or is this a design flaw?

e.g.

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket {
     ...
    // initiate the first read
    self.socket = newSocket;
    [self.socket readDataWithTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    // do what you need with the data...

    // read again, or didReadData won't get called!
    [self.socket readDataWithTimeout:-1 tag:0];
}
like image 314
Boon Avatar asked Feb 23 '26 17:02

Boon


1 Answers

Why is it designed that way?

As long as you're only ever using readDataWithTimeout:tag: it may seem more intuitive to just have the delegate method called whenever some new data has arrived.

But readDataWithTimeout:tag: isn't the the only way to read data with GCDAsyncSocket. There are also e.g. readDataToLength:withTimeout:tag: and readDataToData:withTimeout:tag:

Both of these methods call the delegate at specific points in the incoming data, and you might want to call different ones at different points in your processing.

For example, if you were handling a stream format where there was a CRLF delimited header followed by a variable length body whose length was provided in the header then you might want to alternate between calls of readDataToData:withTimeout:tag: to read the header whose delimiter you know, and then readDataToLength:withTimeout:tag: to read the body whose length you have pulled from the header.

like image 140
Simon Jenkins Avatar answered Feb 26 '26 09:02

Simon Jenkins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!