1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Greg
  • 1,225
  • 3
  • 16
  • 35
  • UPDATE: even when I check [stream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] right after I call [stream write:], it's (null). – Greg Jul 30 '12 at 14:41
  • Any update on this one. Did you eventually manage to figure it out? – Alex Aug 26 '12 at 17:03

1 Answers1

1

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.

Alex
  • 7,432
  • 20
  • 75
  • 118