![](/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.