建立与流媒体服务器和iphone的套接字连接

时间:2011-05-13 06:39:37

标签: iphone sockets streaming

我想建立与流媒体服务器(使用iphone)的套接字连接,并希望将其内容(如图像,.css等)下载到iphone。任何想法或示例代码都可以帮助我。我只需要为客户编写代码。

2 个答案:

答案 0 :(得分:3)

按如下方式建立连接,并将urlStr更改为您的服务器URL

    NSString *urlStr = @"http://192.168.0.108";
    NSURL *website = [NSURL URLWithString:urlStr];
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[website host], 1234, &readStream, &writeStream);
    NSInputStream *inputStream = (NSInputStream *)readStream;
    NSOutputStream *outputStream = (NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];

按如下方式使用NSStream Delegate读取数据

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {

    switch(eventCode) {
        case NSStreamEventHasBytesAvailable:

        {

            NSLog(@"Bytes Available");


            uint8_t b[1024];
            unsigned int len = 0;
            NSMutableData *data = [[NSMutableData alloc] init];
            len = [(NSInputStream *)stream read:b maxLength:1024];


            if(!len) {
                if ([stream streamStatus] != NSStreamStatusAtEnd)
                {

                }
            } else {

                [data appendBytes:(const void *)b length:len];
                int bytesRead;
                bytesRead += len;
               //make use of data here

        }
        }

            break;

    }

}

答案 1 :(得分:-2)

我使用的代码略有变化:

NSHost *host = [NSHost hostWithName:[website host]];
        [NSStream getStreamsToHost:host 
                      port:8766 
                       inputStream:iStream
                      outputStream:oStream];

而不是

CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[website host], 1234, &readStream, &writeStream);
    NSInputStream *inputStream = (NSInputStream *)readStream;
    NSOutputStream *outputStream = (NSOutputStream *)writeStream;