问题
Is it possible to do the following with AsyncSocket:
while ("response packet" is not read) do {
- Read at least first 5 bytes from read stream, and extract "response packet" length size from that.
- Read further until reached reading amount of bytes defined in "response packet" header.
- If reached the end of read stream but some bytes are lacking then wait for another read stream and finish reading the "response packet" then.
- Copy read bytes into buffer and mark that read data as "response packet" data.
- Do callback to my delegate onSocket:didReadData:withTag: with that data.
- clear buffer (response packet) and do the same steps with next read streams.
}
Here's my current usage of AsyncSocket:
I'm writing a data via socket with AsyncSocket:
[_socket writeData:request withTimeout:commandData tag:commandTag];
and receiving a callback in my delegate class:
onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
The problem is, there's no terminating char in data stream and the only way to distinguish the length of comming "response packets" is to read and parse their first 5 bytes and use that for cutting data into "packets" and making callbacks to my delegate. Currently, I'm using AsyncSocket as shown in code fragment above, and some callbacks "onSocket:didReadData:withTag:" are already good length data packets (received NSData), but some are merged. IMHO I need explicitly to tell AsyncSocket how to interpret and cut coming data into packets when reading.
回答1:
Found the solution. You need to call onSocket:didWriteDataWithTag: in AsyncSocket delegate method:
- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
...
[sock readDataToLength:<preferred size of response packet> withTimeout:myTimeout tag:tag];
//instead of
//[sock readDataWithTimeout:myTimeout tag:tag];
}
This way you define when onSocket:didReadData:withTag: will be called.
来源:https://stackoverflow.com/questions/9410754/asyncsocket-how-to-define-read-length-and-get-callback-only-when-read-length-is