1

我的应用程序使用 NSInputStream,如下所示:

inputStream.delegate = self;
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [readStream open];

并委托:

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent

它工作正常,但我做的所有其他请求,它排队直到第一个完成。我一次可以做一个,没有办法做多个并发请求。

有解决办法吗?谢谢

这个解决方案对我不起作用: https ://stackoverflow.com/a/15346292/1376961

更新:我的服务器是否无法处理来自同一来源的多个连接。

4

3 回答 3

2

您将需要在单独的线程中创建流以使它们能够同时工作。我假设您有一个方法可以设置您提到的 inputStream:

- (void)openStreamInNewThread {
    [NSThread detachNewThreadSelector:@selector(openStream) toTarget:self withObject:nil];
}

- (void)openStream {
    NSInputStream *inputStream;

    // stream  setup

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                   forMode:NSRunLoopCommonModes];
}

请注意,这[NSRunLoop currentRunLoop]将返回当前线程的运行循环。因此,您让新创建的流在单独的线程中运行,同时在它们自己的线程中与其他流一起加载数据。

于 2015-11-08T00:53:32.843 回答
1

您可以尝试将每个流安排在其自己的运行循环中。下面是模拟类中的一种改进方法,旨在对我的POSInputStreamLibrary进行单元测试:

static const NSTimeInterval kRunLoopCycleInterval = 0.01f;
static const uint64_t kDispatchDeltaNanoSec = 250000000;

- (POSRunLoopResult)launchNSRunLoopWithStream:(NSInputStream *)stream delegate:(id<NSStreamDelegate>)streamDelegate {
    stream.delegate = streamDelegate;
    __block BOOL breakRunLoop = NO;
    __block dispatch_semaphore_t doneSemaphore = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [stream scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
        if ([stream streamStatus] == NSStreamStatusNotOpen) {
            NSLog(@"%@: opening stream...", [NSThread currentThread]);
            [stream open];
        }
        while ([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:kRunLoopCycleInterval]] && !breakRunLoop)
        {}
        NSLog(@"%@: We are done!", [NSThread currentThread]);
        dispatch_semaphore_signal(doneSemaphore);
    });
    POSRunLoopResult result = dispatch_semaphore_wait(doneSemaphore, dispatch_time(DISPATCH_TIME_NOW, kDispatchDeltaNanoSec)) == 0 ? POSRunLoopResultDone : POSRunLoopResultTimeout;
    if (POSRunLoopResultTimeout == result) {
        breakRunLoop = YES;
        dispatch_semaphore_wait(doneSemaphore, DISPATCH_TIME_FOREVER);
    }
    return result;
}
于 2015-11-09T10:17:37.503 回答
1

每次创建新的 NSInputStream 时,我都会将其添加到块对象中,然后将块对象存储在 NSMutableArray 中。

我发布了将视频从一个 iOS 流式传输到另一个 iOS 的代码:

https://app.box.com/s/94dcm9qjk8giuar08305qspdbe0pc784

使用 Xcode 11 构建这个应用程序;在两台 iOS 11 设备上运行它。

触摸两台设备之一上的相机图标以开始流式传输实时视频。

如果您没有两台设备,可以在模拟器中运行应用程序;但是,只能从真实设备流式传输(相机在模拟器上不可用)。

于 2017-09-14T02:04:11.447 回答