![](/img/trans.png)
[英]How do I read an NSInputStream while writing it to an NSOutputStream in iOS?
[英]iOS how can i perform multiple NSInputStream
我的应用程序使用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
更新:是我的服务器无法处理来自同一源的多个连接。
您将需要在单独的线程中创建流,以使它们能够同时工作。 我假设您有一个方法可以设置您引用的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]
将返回当前线程的运行循环。 因此,您需要在单独的线程中运行新创建的流,并在其自己的线程中同时加载其他数据。
您可以尝试将每个流安排在其自己的运行循环中。 下面是来自模拟类的一种改进方法,该类旨在对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;
}
每次创建新的NSInputStream时,都会将其添加到块对象中,然后将其存储在NSMutableArray中。
我发布了将视频从一个iOS流到另一个iOS的代码:
https://app.box.com/s/94dcm9qjk8giuar08305qspdbe0pc784
使用Xcode 11构建该应用; 在两个iOS 11设备上运行它。
触摸两个设备之一上的“相机”图标以开始流式传输实时视频。
如果没有两个设备,则可以在模拟器中运行该应用程序; 但是,仅来自真实设备的流(相机在模拟器上不可用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.