Dave Kasper
Dave Kasper

Reputation: 1389

NSStream hangs on close

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.

Upvotes: 3

Views: 1451

Answers (3)

fshbn
fshbn

Reputation: 74

Retaining the NSOutputStream solves my problem, hope it helps to others. Sample codes are written with ARC so They don't need to retain anymore but If you don't use ARC, You have to retain.

NSOutputStream *outputStream = (NSOutputStream *)CFBridgingRelease(writeStream);
**[outputStream retain];**
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop]
                                forMode:NSDefaultRunLoopMode];
[outputStream open];

Upvotes: 0

b005t3r
b005t3r

Reputation: 815

Most likely you didn't retain your input and output streams after receiving them :) I had exactly the same problem, but it costed me much time to find the solution :)

Upvotes: 2

Shaggy Frog
Shaggy Frog

Reputation: 27601

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;
    ...

Upvotes: 1

Related Questions