I searched the website for a long time ... I did not find the answer to the question, so I decided to publish it here. I am trying to establish a connection to an NNTP server using NSStream.
In a test program, I open streams and send a message. The delegate method ( stream:handleEvent:
is called twice for the output stream ( NSStreamEventOpenCompleted
, NSStreamEventHasSpaceAvailable
), but never for the input stream!
Why does the input never call a delegate? Any ideas?
Basically, the code is as follows:
init and open threads:
CFReadStreamRef tmpiStream; CFWriteStreamRef tmpoStream; CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)SERVER, PORT, &tmpiStream, &tmpoStream); iStream = (__bridge NSInputStream *) tmpiStream; oStream = (__bridge NSOutputStream *)tmpoStream; [iStream setDelegate:self]; [oStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream open]; [oStream open];
send a message:
NSData *data = [[NSData alloc] initWithData:[messageString dataUsingEncoding:NSASCIIStringEncoding]]; [oStream write:[data bytes] maxLength:[data length]];
receive messages:
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { NSLog(@"EventCode: %i", eventCode);
The class that contains this code inherits from NSObjects and implements NSStreamDelegate
. (iOS5 with ARC)
Thanks for any help!
EDIT: I just tried polling after opening threads like this - it works:
while (![iStream hasBytesAvailable]) {} uint8_t buffer[1024]; int len; NSString *str = @""; while ([iStream hasBytesAvailable]) { len = [iStream read:buffer maxLength:sizeof(buffer)]; if (len > 0) { NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSISOLatin1StringEncoding]; if (output != nil) { str = [str stringByAppendingString:output]; } } } NSLog(@"Response: %@", str);
But of course I still need a better (asynchronous) solution;)