尝试使用GCDAsyncSocket进行缓冲传输

时间:2013-03-18 17:20:45

标签: ios objective-c http gcdasyncsocket nsinputstream

(更新)我正在尝试读取大文件(视频或图片)并通过SOAP请求将其发送到远程服务器。我需要将数据编码为Base64字符串。我试着这样做:

  • 为SOAP请求创建一个模板xml,它将“围绕”base64编码数据

  • 将SOAP xml的第一部分推送到缓冲区

  • 打开视频文件并将其编码为块并将每个编码块推入缓冲区

  • 最后,推送SOAP xml的第二部分

为了能够如上所述“排队”部分,我试图使用GCDAsyncSocket及其缓冲功能。我认为,由于GCDAsyncSocket在TCP级别上运行,我需要自己编写HTTP POST头。所以,有许多活动部分我只是模糊地理解,而且我可能会错误地完成这一切。但我的套接字似乎永远不会起飞,我甚至不确定如何调试它。这是我的相关代码,试着看看你是否发现了任何明显的错误:

NSString *soapBody = ...; //Create the SOAP xml here with the part in the middle reserved for the Base64 encoded data (marked with string "CUT_HERE";
NSArray *soapBodyArray = [soapBody componentsSeparatedByString:@"CUT_HERE"];
self.p_soapBodyPart1 = [soapBodyArray[0] dataUsingEncoding:NSUTF8StringEncoding];
self.p_soapBodyPart2 = [soapBodyArray[1] dataUsingEncoding:NSUTF8StringEncoding];
socketQueue = dispatch_queue_create("socketQueue", NULL);//socketQueue is an ivar
self.p_socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQueue];//create the socket
NSError *err = nil;
if (![p_socket connectToHost:myURL onPort:80 error:&err]) // Asynchronous!
{
   NSLog(@"I goofed: %@", err);
   return;
}
NSString* httpHeader = [NSString stringWithFormat:@"POST %@ HTTP/1.1\r\nHost: %@\r\nAccept-Encoding: gzip, deflate\r\nContent-Type: text/xml\r\nAccept-Language: en-us\r\nAccept: */*\r\nSOAPAction: http://tempuri.org/myAction\r\nConnection: keep-alive\r\nUser-Agent: ...\r\n\r\n", webserviceOperationsPath, webserviceHost];//Create the HTTP POST header 
[p_socket writeData:[httpHeader dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1]; //enqueue the HTTP header
[p_socket writeData:self.p_soapBodyPart1 withTimeout:-1 tag:2]; //enqueue the first part of the SOAP xml
[self setUpStreamsForInputFile: [self.p_mediaURL path]];//set up NSInputStream to read from media file and encode it as Base64

套接字似乎总是连接好,我用这个委托方法看到了:

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"Socket Connected");
}

setUpStreamsForInputFile方法(在上面的第一个代码清单中调用):

- (void)setUpStreamsForInputFile:(NSString *)inpath {
    self.p_iStream = [[NSInputStream alloc] initWithFileAtPath:inpath];
    [p_iStream setDelegate:self];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    dispatch_async(queue, ^ {
        [p_iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSDefaultRunLoopMode];
        [p_iStream open];
        [[NSRunLoop currentRunLoop] run];
    });
}

现在,上一个方法中的NSInputStream设置将向此委托发送事件:

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
    switch(eventCode) {
        case NSStreamEventHasBytesAvailable:
        {
            if (stream == self.p_iStream){
                if(!self.p_tempMutableData) {
                    self.p_tempMutableData = [NSMutableData data];
                }
                uint8_t buf[24000];
                unsigned int len = 0;
                len = [p_iStream read:buf maxLength:24000];//read a chunk from the file
                if(len) {
                        [p_tempMutableData appendBytes:(const void *)buf length:len];
                        NSString* base64encData = [Base64 encodeBase64WithData:self.p_tempMutableData];//encode the chunk
                        self.p_streamEncData = [base64encData dataUsingEncoding:NSUTF8StringEncoding];
                        [p_socket writeData:self.p_streamEncData withTimeout:-1 tag:3];//write the encoded chunk to the socket 
                }   
            }
            break;
        }
        case NSStreamEventEndEncountered:
        {
            [stream close];
            [stream removeFromRunLoop:[NSRunLoop currentRunLoop]
                              forMode:NSDefaultRunLoopMode];
            stream = nil;
            [p_socket writeData:self.p_soapBodyPart2 withTimeout:-1 tag:4];//write the second part of SOAP xml
            break;
        }
        ... //some other events handled here
    }
}

套接字应该使用此委托

将内容输出到日志中
- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    if (tag == 1)
        NSLog(@"HTTP Header Written");
    else if (tag == 2)
        NSLog(@"Soap Part 1 written");
    else if (tag == 3)
        NSLog(@"File written");
    else if (tag == 4)
        NSLog(@"Soap Part 2 written");
}

但这种情况随机发生。例如,有时我会看到前2个被调用,有时不会被调用。当我这样做并且它到达第三个“if”(我正在编写实际编码数据的那个)时,它只写了2到3次就是它 - 考虑到文件的大小,我认为太少了。我从来没有看到它到达最后的“if”,它应该写出SOAP xml的最后一部分。 非常感谢任何帮助!提前谢谢。

进一步更新(3/19/13)

今天测试套接字我根本不再接受写事件,这告诉我它是随机的,我正在做一些非常错误的事情。今天连接打开但在某些时候超时,正如我可以看到以下委托方法:

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{    // This method is executed on the socketQueue (not the main thread)
    dispatch_async(dispatch_get_main_queue(), ^{
        @autoreleasepool {
            NSLog(@"socketDidDisconnect:withError: \"%@\"", err);
        }
    });
}

返回

socketDidDisconnect:withError:“Error Domain = NSPOSIXErrorDomain Code = 60”操作超时“UserInfo = 0x1cd89b00 {NSLocalizedFailureReason = connect()函数错误,NSLocalizedDescription =操作超时}”

当我仍然在上面的流委托中运行Base64数据的写入时。

0 个答案:

没有答案