我有一个TCP连接类,它使用NSStreamDelegate
并且工作正常。它接收消息并在任何事情中对它们做出响应。在某些情况下,它应该打开第二个连接。这是第二类,与第一类非常相似。
在打开时,第一个类应该等到流报告打开状态:
- (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...");
}
我的问题是,没有调用流委托方法-stream:handleEvent:
。
我在我的第一堂课中使用了几乎完全相同的代码。即使我删除dispatch_semaphore_wait();
调用,代理方法也不会触发。
在我不等的情况下,我可以写入流。但我必须在异步环境(第一类)中实现超时。
我在第一个类的-openWithTimeoutBlock:
方法中调用-stream:handleEvent:
方法。可能会中断第二个班级NSStreamDelegate
吗?
任何想法如何解决?