AsyncSocket 委托方法调用不正确?
我正在使用 AsyncSocket 类通过本地网络将相当大的图像从 iPhone 传输到 Mac。在 header 中,didReadData 委托方法声明如下:
/**
* Called when a socket has completed reading the requested data into memory.
* Not called if there is an error.
**/
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
它表示当套接字完成读取数据时将调用该方法。然而,该方法被调用多次,每次数据长度都会增加。我如何知道下载何时完成?我的意思是在前几个字节中发送数据的长度吗?
I'm transferring a reasonably large image over a local network from an iPhone to Mac using the AsyncSocket class. In the header the didReadData delegate method is declared as below:
/**
* Called when a socket has completed reading the requested data into memory.
* Not called if there is an error.
**/
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
It says this method will be called when the socket has completed reading the data. However this method is called many times, each time data length increasing. How am I meant to know when the download is finished? Am I meant to send the length of the data in the first few bytes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当套接字完成读取数据时,确实会调用该委托方法。等式中缺少的部分是告诉
AsyncSocket
接收到的数据何时完成。它不理解您尝试接收的数据,您必须告诉它 - 正如您在最后一个问题中提到的那样。这就是
AsyncSocket
真正发挥作用的地方。您确实可以发送以其长度为前缀的图像,并让该类发挥其魔力。您的代码将类似于以下内容。在您的委托方法中:
当然,如果您要传输相当大的图像,您可能需要跟踪您的进度。为此,有
-[AsyncSocket ProgressOfReadReturningTag:bytesDone:total:]
实例方法。还有-[id; onSocket:didReadPartialDataOfLength:tag:]
委托方法。That delegate method will indeed be called when the socket has completed reading the data. The missing part of the equation is telling the
AsyncSocket
when the received data is complete. It has no understanding of the data you're trying to receive, you have to tell it -- as you alluded to in your final question.This is where
AsyncSocket
really shines. You can indeed send the image prefixed by its length and let the class work its magic. Your code would look something like the following.In your delegate method:
Of course, if you are transferring reasonably large images, you may want to keep track of your progress. For this purpose, there is the
-[AsyncSocket progressOfReadReturningTag:bytesDone:total:]
instance method. There's also the-[id<AsyncSocketDelegate> onSocket:didReadPartialDataOfLength:tag:]
delegate method.