1

I'm trying to upload a linear file under http in streaming mode. The idea is do this steps simultaneously, 1) Thread 1: record an audio file and store it in a temp file 2) Thread 2: Take n bytes from temp file and send it to an http server.

How can I write an http stream?, On CFHTTPStream I did not see write methods, only read :s Do I need use sockets? Thanks!!!

My actual code is

   CFWriteStreamRef stream;
   NSString *strUrl = @"myurl";       
   NSURL *url = [[[NSURL alloc] initWithString:strUrl] retain];

   CFStringRef requestMethod = CFSTR("GET");

   CFHTTPMessageRef message= CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, (CFURLRef)url, kCFHTTPVersion1_1);

    CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Content-Type"),
                                     CFSTR("multipart/form-data"));
   stream =  ??  //CFReadStreamCreateForHTTPRequest(NULL, message);
    CFRelease(message);
  //other headers...        
    if (CFWriteStreamSetProperty(stream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue)  == false)
    {
        NSLog(@"Error");
        return NO;
    }


    //
    // Open the stream
    //
    if (!CFWriteStreamOpen(stream))
    {
        CFRelease(stream);
        NSLog(@"Error");
        return NO;
    }

    CFStreamClientContext context = {0, self, NULL, NULL, NULL};
    CFWriteStreamSetClient(stram, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
                           RSWriteStreamCallBack,
                           &context);
    CFWriteStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
4

1 回答 1

3

解决方案是创建一个NSInputStream的子类,并实现方法open、close、read、hasBytesAvailable并且不要忘记-(NSStreamStatus)streamStatus。最后一个方法从 http 调用,以了解我们是打开、关闭还是完成 (NSStreamStatusAtEnd) 发送(还有其他状态,但这是最重要的)。我使用像缓冲区这样的 tmp 文件,因为我必须发送大量数据,但也许数据内存缓冲区可能会更好。最后,我实现了使用自定义 NSInputStream 的其他类,代码如下:

    NSURL *url = [NSURL URLWithString:@"url"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req setHTTPMethod:@"POST"];
    //set headers if you have to do for example: 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data"];
    [req setValue:contentType forHTTPHeaderField:@"Content-Type"];
    //Create your own InputStream
    instream = [[CustomStream alloc] init];
    [req setHTTPBodyStream:instream];
    //I remove instream later 
      NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
    [aConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [aConnection start]; 
于 2012-05-21T21:19:00.490 回答