私はNSStream
自分の生活を楽にするためにラッパーのようなものを書こうとしています。接続が確立されたとき、閉じられたとき、データを書き込んで受信データを取得するタイミングを知りたいだけです。だから私はこのようなことを考えています:
ヘッダ:
@interface StreamWrapper : NSObject
- (id)initWithDelegate:(id <StreamWrapperDelegate>)delegate;
- (void)writeData:(NSData *)data;
@end
@protocol StreamWrapperDelegate <NSObject>
@required
- (void)streamWrapper:(StreamWrapper *)streamWrapper didReceiveData:(NSData *)data;
- (void)streamWrapperDidConnect:(StreamWrapper *)streamWrapper;
- (void)streamWrapperDidCloseConnection:(StreamWrapper *)streamWrapper;
@end
クラス:
@interface StreamWrapper () <NSStreamDelegate>
...
@property (nonatomic, weak) id <StreamWrapperDelegate> delegate;
@property (nonatomic, strong) NSInputStream *inputStream;
@property (nonatomic, strong) NSOutputStream *outputStream;
- (void)closeStreams;
- (void)setAndOpenStreams;
@end
@implementation StreamWrapper
#pragma mark - NSStreamDelegate
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventEndEncountered:
// Should I here close both streams (even if this is called only for one (in or out)) and delegate closed connection?
break;
case NSStreamEventErrorOccurred:
// Should I here close both streams (even if this is called only for one (in or out)) and delegate closed connection?
break;
case NSStreamEventHasBytesAvailable:
// My reading algorithm...
[self.delegate streamWrapper:self didReceiveData:data];
break;
case NSStreamEventHasSpaceAvailable:
// Is this useful for me?
break;
case NSStreamEventNone:
// Is this useful for me?
break;
case NSStreamEventOpenCompleted:
// Should I here delegate successful connection? Should I wait to receive this for both streams? How?
break;
default:
break;
}
}
...
@end
それで...接続が確立され、データを送受信できるようになり、接続が切断されたとき(一方向でも)を常に把握し、接続を閉じて新しい確立を試みる必要があることを実装するにはどうすればよいですか?または、このようなことを行うための適切な方法は何ですか?