Stream for receiving data - NSInputStream

Everything,

I have a server with a tcp socket stream for communication. I need to get to this stream and read the initial data that it needs to send to me.

My current code is as follows. Honestly, I'm going to make it completely blind. I'm not sure if this is correct, not to mention the correct operation.

-(void) initNetworkCommunication { //input stream NSInputStream *iStream; NSURL *url = [url initWithString:@"192.168.17.1:2004"]; [iStream initWithURL:url]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream open]; } 

So, by the way I see it, this code initializes the stream, but how do I read from the stream?

thanks

+5
objective-c iphone xcode nsstream
source share
1 answer

There are two ways to get data from a stream: polling and using stream events.

Polling is simpler, but will block the thread in which it is running. If you use this method, you do not need to make calls to setDelegate: or scheduleInRunLoop:forMode: Polling is done by calling read:maxLength: .

 NSInteger result; uint8_t buffer[BUFFER_LEN]; // BUFFER_LEN can be any positive integer while((result = [iStream read:buffer maxLength:BUFFER_LEN]) != 0) { if(result > 0) { // buffer contains result bytes of data to be handled } else { // The stream had an error. You can get an NSError object using [iStream streamError] } } // Either the stream ran out of data or there was an error 

Using thread events requires installing a delegate and adding a thread to the run loop. Instead of blocking the stream, the stream sends a stream:handleEvent: message to its delegate when certain events occur, including when data is received. The delegate can then retrieve the data from the stream. The following is an example of the stream:handleEvent: method:

 - (void)stream:(NSInputStream *)iStream handleEvent:(NSStreamEvent)event { BOOL shouldClose = NO; switch(event) { case NSStreamEventEndEncountered: shouldClose = YES; // If all data hasn't been read, fall through to the "has bytes" event if(![iStream hasBytesAvailable]) break; case NSStreamEventHasBytesAvailable: ; // We need a semicolon here before we can declare local variables uint8_t *buffer; NSUInteger length; BOOL freeBuffer = NO; // The stream has data. Try to get its internal buffer instead of creating one if(![iStream getBuffer:&buffer length:&length]) { // The stream couldn't provide its internal buffer. We have to make one ourselves buffer = malloc(BUFFER_LEN * sizeof(uint8_t)); freeBuffer = YES; NSInteger result = [iStream read:buffer maxLength:BUFFER_LEN]; if(result < 0) { // error copying to buffer break; } length = result; } // length bytes of data in buffer if(freeBuffer) free(buffer); break; case NSStreamEventErrorOccurred: // some other error shouldClose = YES; break; } if(shouldClose) [iStream close]; } 
+18
source share

All Articles