So, looking at your NSStreamDelegate
, it looks like you haven't implemented all of the cases for that switch statement. I recently wrote an IRC client for OS X that uses NSStream
and NSStreamDelegate
in a very similar way, and I'm pretty sure that the compiler should complain when you haven't checked for all of the cases there.
Looking back to some of my code it looks like you should be checking for the cases
NSStreamEventHasSpaceAvailable
NSStreamEventOpenCompleted
NSStreamEventHasBytesAvailable
NSStreamEventEndEncountered
NSStreamEventErrorOccurred
So the case you haven't checked for is NSStreamEventHasSpaceAvailable
, which is when you can start writing to your stream.
edit: Reading your code again, I see in your sendMessage
action that you're using the outputStream
object instead of the delegate to write, and then doing the work yourself to read from the inputStream
. I think you probably want to use the delegate and never read directly from your inputstream because it will greatly simplify how your code receives data from the network. From what I understand, NSStream
is there to provide a small layer of abstraction around the fact that data is buffered from the network so you don't need to do things like call usleep
while your inputstream does not have bytes available to read.
edit2: I read your update about your code never getting past while (![inputStream hasBytesAvailable])
and it seems pretty clear that the problem is that you're not using your streams correctly. The way I see it, the best way to use NSStream
is to respond to events, using its handleEvent:(NSStreamEvent) event
method, and never directly tell it to write bytes, or to sleep until it has bytes available.
In the code I linked to you, I have a readDelegate and a writeDelegate that both handle NSStreams
, you might want to take a look at how I use my writeDelegate here. I basically have a method, addCommand:(NSString *) command
that puts a string to write to the stream into a queue, and then when my stream delegate can write bytes (NSStreamEventHasSpaceAvailable
), I write as many bytes as I can. I hope this helps!