を使用して正常に動作する TCP 接続クラスがありますNSStreamDelegate
。それはメッセージを受け取り、どんな問題でもそれらに応答します。場合によっては、2 番目の接続を開く必要があります。これは、最初のクラスと非常によく似た 2 番目のクラスです。
オープン時に、最初のクラスは、ストリームがオープン状態を報告するまで待機する必要があります。
- (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:
それは2番目のクラスを中断できますNSStreamDelegate
か?
それを修正する方法はありますか?