如何计算发送/接收的字节数,包括iOS HTTP连接中的TCP/IP开销



我正在使用nsurlconnection与服务器执行HTTP通信。我希望找出我的应用程序发送/接收的确切字节数,包括TCP/IP开销。在大量研究之后,还没有找到有关如何实现这一目标的任何有用信息。

如果使用它可以帮助我解决这个问题,我愿意切换到CFStream。预先感谢。

在控制器的.h中,我声明了两个vars:

NSMutableData *_data;
float downloadSize;

也不要忘记.h

中的代表
@interface SomeViewController : UIViewController <NSURLConnectionDataDelegate, NSURLConnectionDelegate>

然后在我的.m:

- (void)connection: (NSURLConnection*) connection didReceiveResponse: (NSHTTPURLResponse*) response
    {
        NSInteger statusCode_ = [response statusCode];
        if (statusCode_ == 200) {
            downloadSize = [response expectedContentLength];
        }
    }
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        if(!_data) _data = [[NSMutableData data]init];
        [_data appendData:data];
        progressView.progress =  ((float) [_data length] / (float) downloadSize);
    }
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
          unsigned char byteBuffer[[_data length]];
          [_data getBytes:byteBuffer];
          [_data writeToFile:pdfPath atomically:YES];
    }

这是我下载PDF文件的控制器。但这可能是什么。当它具有响应时,它会获得预期的长度,然后每次收到数据时,都会将其附加到我的可变数据中,然后将其比较到预期的大小。

希望这会有所帮助:D

最新更新