NSStreamDelegate not receiving messages

368 views Asked by At

I have a TCP connection class which uses the NSStreamDelegate and works fine. It receives messages and respond to them in any matter. In some cases it should open a second connection. This is a second class which is quite similar to the first one.

On open, the first class should wait until the streams report open state:

- (BOOL)connectDataConnection {
    __block BOOL connected = YES;
    _dataConnection = [JWTCPConnection connectionWithInputStream:(__bridge NSInputStream *)readStream and outputStream:(__bridge NSOutputStream *)writeStream];
    [_dataConnection openWithTimeoutBlock:^{
        connected = NO;
    }];

    return connected;
}


// JWTCPConnection

- (id)initWithInputStream:(NSInputStream *)inStream andOutputStream:(NSOutputStream *)outStream {
    if (self = [super init]) {
        _iStream = inStream;
        _oStream = outStream;

        [_iStream setDelegate:self];
        [_oStream setDelegate:self];

        [_iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] foreMode:NSRunLoopCommonModes];
        [_oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] foreMode:NSRunLoopCommonModes];
    }

    return self;
}

- (void)openWithTimeoutBlock:(void (^)())timeoutBlock {
    _timeoutBlock = timeoutBlock;

    float seconds = 5.0;
    dispatch_time_t dispatchTime = dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC);
    dispatch_queue_t dispatchQueue = dispatch_queue_create("com.company.app", 0);

    dispatch_async(dispatchQueue, ^{
        dispatch_after(, dispatchTime, dispatchQueue, ^{
            if (_timeoutBlock) {
                _timeoutBlock();
                [self close];
            }

            dispatch_semaphore_signal(_connectionSemaphore);
        });
    });

    _connectionSemaphore = dispatch_semaphore_create(0);

    [_iStream open];
    [_oStream open];

    dispatch_semaphore_wait(_connectionSemaphore, DISPATCH_TIME_FOREVER);
}

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
    NSLog(@"a stream handels event...");
}

My problem is, that the stream delegate method -stream:handleEvent: does not get called.

I use almost the identical code in my first class, which works. Even when I remove the dispatch_semaphore_wait(); call, the delegate method doesn't fire.

In the case I don't wait, I can write to the stream. But I have to implement a timeout in an asynchronous environment (of the first class).

I call the -openWithTimeoutBlock: method inside the -stream:handleEvent: method of the first class. Could that interrupt the second classes NSStreamDelegate?

Any ideas how to fix that?

0

There are 0 answers