IPhone SDK sends string via Wi-Fi

I'm trying to add a simple function to my application, it should just send a pre-formatted string to another device, very similar to the WiTap example code. This sounds very trivial, but I can't get it to work: (How can I change WiTap to send a string instead of a single int?

Any pointers to good lessons would be great.

I looked at the SimpleNetworkStreams sample, but it went through my head as I only want to send a string (NSString, char [], has no preference), not a file.

I looked at this example: How to add data to NSOutputStream? but it also did not help.

+6
iphone network-programming
source share
1 answer

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.

+4
source share

All Articles