NSOutputStream not writing data properly

1.7k views Asked by At

Using the NSStreamEventHasSpace available event, I am trying to write a simple NSString to to an NSOutputStream. Here is the contents of that event:

uint8_t *readBytes = (uint8_t *)[data mutableBytes];
readBytes += byteIndex; // instance variable to move pointer
int data_len = [data length];
unsigned int len = ((data_len - byteIndex >= 12) ?
                            12 : (data_len-byteIndex));
uint8_t buf[len];
(void)memcpy(buf, readBytes, len);
len = [output write:(const uint8_t *)buf maxLength:len];
NSLog(@"wrote: %s", buf);
byteIndex += len;

I pretty much took it right from Apple. The data is initialized in my viewDidLoad method with

data = [NSMutableData dataWithData:[@"test message" dataUsingEncoding:NSUTF8StringEncoding]];
[data retain];

The HasSpaceAvailable event is called twice. In the first one, the entire message is written with the characters "N." appended to it. In the second time, NSLog reports that a blank message was written (not null). Then, the EndEncountered event occurs. In that event, I have

NSLog(@"event: end encountered");
assert([stream isEqual:output]);
NSData *newData = [output propertyForKey: NSStreamDataWrittenToMemoryStreamKey];
if (!newData) {
    NSLog(@"No data written to memory!");
} else {
    NSLog(@"finished writing: %@", newData);
}
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
                  forMode:NSDefaultRunLoopMode];
[stream release];
output = nil;
break;

I also got this from Apple. However, "No data written to memory!" is logged. No errors occur at anytime, and no data appears to have been received on the other end.

1

There are 1 answers

0
Alex On

I seem to have fixed this by using low level Core Foundation methods instead of higher level NSStream methods. I used this article as a starting point:

http://oreilly.com/iphone/excerpts/iphone-sdk/network-programming.html

It covers input and output streams in great lenghts and has code examples.

Hope this helps.