我想寫一些像NSStream
包裝的東西,使我的生活更輕鬆。我只想知道什麼時候建立連接,什麼時候關閉,寫入一些獲取數據的數據。所以我想是這樣的:確定通過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
所以......如何實現,我將永遠知道在連接建立的時候和我能夠發送和接收數據,什麼時候連接斷開(甚至只有一種方式),我應該關閉它並嘗試新的設置?或者什麼是正確的方式來做這樣的事情?
我討厭這種答案,但在這種情況下,我配得上它。 – user500
如果它不解決您的問題,我可以爲您提供一個示例源代碼。我正在研究的那個 –
嗯,我想現在我能夠做到這一點,但如果可能的話,我也希望看到您的解決方案。 – user500