ORL
ORL

Reputation: 618

NSInputStream example?

I'm trying to create a simple iPhone app that can communicate with a server (which is running on my computer at the moment and works fine). I've been trying to use the NSStream class but have had a lot of issues. I really just want to mimic a telnet-type of connection using the streams. I've managed to send data to my server with an NSOutputStream, but I can't figure out how to use the NSInputStream to read the reply sent from the server. Here is the method I have so far:

    -(void)sendName:(NSString *)name{
NSData*nameData = [name dataUsingEncoding:NSUTF8StringEncoding];
[outputStream write:(uint8_t *)[nameData bytes] maxLength:[nameData length]];

    //The server sends a reply here.
    [inputStream read:? maxLength:?]; // I don't know what do to here.


[inputStream close]; //Created and opened elsewhere.
[outputStream close]; //Created and opened elsewhere.
    }

I can't figure out how to get the inputStream to read what the server sends. I've tried passing an NSData object in as the buffer but it always crashes. So how do I create the buffer? Also, is it bad to make the length huge to make sure the buffer doesn't fill up (though maybe waste space)? Some example code would be splendid! Thanks in advance!

Upvotes: 2

Views: 9796

Answers (1)

NSResponder
NSResponder

Reputation: 16861

The thing you need to understand about NSStreams, is "don't call us, we'll call you." When the stream has data available, it will notify its delegate, and then you read whatever data is available and tell it to go get some more.

Read the Streams Programming Guide

Upvotes: 3

Related Questions