我正在尝试编写类似包装器的东西,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
那么......如何实现我将始终知道何时建立连接并且我能够发送和接收数据以及何时断开连接(即使只有一种方式)并且我应该关闭它并尝试全新的建立?或者什么是做这样的事情的正确方法?