1

私のアプリは、以下のように NSInputStream を使用します。

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

そしてデリゲート:

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

それは正常に動作しますが、私が行う他のすべての要求は、最初に完了するまでキューに入れられました。1 回に 1 つずつ実行できますが、複数の同時要求を実行する方法はありません。

解決策はありますか?ありがとうございました

この解決策は私にはうまくいきません: https://stackoverflow.com/a/15346292/1376961

更新: 私のサーバーは同じソースからの複数の接続を処理できませんでした。

4

3 に答える 3

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 に答える