I have since realized this and decided to answer my own question here in the interests of those in a similar situation.
Whenever I want to send any string, I use this helper function that I created:
- (void) send:(NSString *)string { const uint8_t *message = (const uint8_t *)[string UTF8String]; if (_outStream && [_outStream hasSpaceAvailable]) if([_outStream write:message maxLength:strlen((char *)message)] == -1) NSLog(@"Failed sending data to peer"); }
On the receiving side, it looks like this:
- (void) stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode { switch(eventCode) { case NSStreamEventHasBytesAvailable: { if (stream == _inStream) { // read it in unsigned int len = 0; len = [_inStream read:buf maxLength:buffSize]; buf[len] = '\0'; if(!len) { if ([stream streamStatus] != NSStreamStatusAtEnd) NSLog(@"Failed reading data from peer"); } else { NSString *message = [NSString stringWithUTF8String:(char *)buf]; // here you do whatever you need with your received NSString *message } } } }
A buffer is defined as:
#define buffSize 60000 uint8_t buf[buffSize];
60,000 is pretty arbitrary, you can change it to suit your needs.
A few notes about this. While it is safe to make the buffer for these lines pretty large, you can never get your line at a time. In the application itself, you must carefully develop a specific protocol that you can rely on to check if you received the entire string and merged the strings received during subsequent NSStreamEvent , if necessary.
Saltynuts
source share