I have an NSInputStream and an NSOutputStream in an iphone app that are connected to a server. I am able to read and write data to the sockets without issue. The problem is that I have a disconnect button, and when I try to call close on either of the streams it hangs the app. I'm guessing that I am trying to call close at the wrong time, but I'm not sure what the right time is.
A:
You have to make sure you're telling the underlying layer to close the native socket for you. Here's some code from one of my apps that does networking:
...
CFReadStreamRef readStreamRef;
CFWriteStreamRef writeStreamRef;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)host, port, &readStreamRef, &writeStreamRef);
if (readStreamRef && writeStreamRef)
{
CFReadStreamSetProperty(readStreamRef, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStreamRef, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
inputStream = (NSInputStream*)readStreamRef;
outputStream = (NSOutputStream*)writeStreamRef;
...
Shaggy Frog
2010-07-23 16:00:30