Hahnemann
Hahnemann

Reputation: 4658

How can I keep an output stream open in Objective-C?

I am writing data to a stream inside event:

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode

As follows (taken from Apple's documentation):

case NSStreamEventHasSpaceAvailable:
    uint8_t *readBytes = (uint8_t *)[self.outData mutableBytes];            
    readBytes += byteIndex;            
    int dataLength = [self.outData length];            
    unsigned int length = ((dataLength - byteIndex >= 1024) ? 1024 : (dataLength - byteIndex));            
    uint8_t buffer[length];            
    (void)memcpy(buffer, readBytes, length);            
    length = [self.outputStream write:(const uint8_t *)buffer maxLength:length];            
    byteIndex += length;            
    break;

However, the event NSStreamEventEndEncountered is called when there is nothing else to write in the output stream, so the output stream is discarded. How can I keep this stream open for writing? According to Apple's documentation this event is called correctly because nothing is written to the output stream. Any ideas?

Upvotes: 0

Views: 2102

Answers (2)

Workshed
Workshed

Reputation: 246

Have you put your streams in a runloop? See the example here: http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server

Upvotes: 1

Peter Hosey
Peter Hosey

Reputation: 96333

The documentation isn't clear on this point, but a reasonable interpretation is that the stream will send NSStreamEventEndEncountered when you have written up to its capacity. (The unclear part is whether this is true of all streams or only those where you specify a capacity. A file-based stream, for example, could send NSStreamEventEndEncountered when the volume that the file is on is full.)

Given that the definition of a “capacity” is that you cannot write more than that much, keeping the stream open past that point doesn't make sense. Even if you have more bytes to write, the stream has no place to put them.

Upvotes: 0

Related Questions