AsyncSocket: how to define read length and get callback only when read length is reached

一个人想着一个人 提交于 2020-01-05 05:25:06

问题


Is it possible to do the following with AsyncSocket:

while ("response packet" is not read) do {

  1. Read at least first 5 bytes from read stream, and extract "response packet" length size from that.
  2. Read further until reached reading amount of bytes defined in "response packet" header.
  3. 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.
  4. Copy read bytes into buffer and mark that read data as "response packet" data.
  5. Do callback to my delegate onSocket:didReadData:withTag: with that data.
  6. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!