我有一个使用NSStreamDelegate
和工作正常的 TCP 连接类。它接收消息并以任何方式响应它们。在某些情况下,它应该打开第二个连接。这是第二类,与第一类非常相似。
打开时,第一个类应该等到流报告打开状态:
- (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
吗?
任何想法如何解决这个问题?