iosnsthreadnsstreamnsinputstreamnsoutputstream

iOS how can i perform multiple NSInputStream


My app uses NSInputStream like below:

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

and delegate:

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

It works fine, but all other requests that i do, it queued until first is finished. I can do one per time and there is no way to do multiple concurrent requests.

There is a solution ? Thank you

This solution not work for me : https://stackoverflow.com/a/15346292/1376961

UPDATE: Was my server can't handle multiple connections from the same source.


Solution

  • You will need to create your streams in separate threads to enable them to work simultaneously. I assume you have a method that sets up the inputStream you referred to:

    - (void)openStreamInNewThread {
        [NSThread detachNewThreadSelector:@selector(openStream) toTarget:self withObject:nil];
    }
    
    - (void)openStream {
        NSInputStream *inputStream;
    
        // stream  setup
    
        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                       forMode:NSRunLoopCommonModes];
    }
    

    Note that [NSRunLoop currentRunLoop] will return the runloop of the current thread. So you have the newly created stream running in a separate thread loading data simultaneously with other streams in their own threads.