I use the following code to connect to server and handle events.
almost copy-paste of http://www.devx.com/wireless/Article/43551
I want to force close the stream before NSStreamEventEndEncountered.
Documentation is lacking and having hard time to figure out how to force close the streams associated with connection. (or close underlying socket if I have to)
Thank you
-(void) connectToServerUsingStream:(NSString *)urlStr
portNo: (uint) portNo {
if (![urlStr isEqualToString:@""]) {
NSURL *website = [NSURL URLWithString:urlStr];
if (!website) {
NSLog(@"%@ is not a valid URL");
return;
} else {
[NSStream getStreamsToHostNamed:urlStr
port:portNo
inputStream:&iStream
outputStream:&oStream];
[iStream retain];
[oStream retain];
[iStream setDelegate:self];
[oStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[oStream open];
[iStream open];
}
}
}
and handles event
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
NSLog(@"stream event %d", eventCode) ;
if( stream == iStream ) NSLog(@"on input stream");
else if( stream == oStream ) NSLog(@"on output stream");
else NSLog(@"on unknown stream identifier") ;
switch(eventCode) {
case NSStreamEventEndEncountered:
{
NSLog(@"stream ended; will be closed") ;
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[stream release];
stream = nil; // stream is ivar, so reinit it
break;
}
case NSStreamEventErrorOccurred:
NSLog(@"stream error") ;
break ;
case NSStreamEventHasBytesAvailable:
//TODO: read here
break ;
case NSStreamEventNone:
NSLog(@"stream null event") ;
break ;
case NSStreamEventOpenCompleted:
NSLog(@"stream is now open") ;
break ;
case NSStreamEventHasSpaceAvailable:
//write here
break ;
}
}
Execute the following method on the thread/runloop that the stream was scheduled on: