views:

165

answers:

1

I'm trying to add a simple feature to my app, it should simply send a pre-formatted string to another device, very much like WiTap sample code does. It sounds like a very trivial thing to do but I cannot get it to work ;(. How can I modify WiTap to send a string instead of a single int?

Any pointers to good tutorials would be great.

I did look at SimpleNetworkStreams sample, but it went way over my head as I'm only looking to send a string (NSString, char[], don't have a preference) and not a file.

Looked at this example too: http://stackoverflow.com/questions/694601/how-to-add-data-for-nsoutputstream but that did not fully help either.

+1  A: 

I have since figured it out and decided to answer my own question here for the benefit of those who are in similar situation.

Whenever I want to send any string, I use this helper function 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
            }
        }
    }
}

The buffer is defined as:

#define buffSize 60000
uint8_t buf[buffSize];

60,000 is fairly arbitrary, you can change it to suit your needs.

A few notes about the above. While it is safe to make the buffer for these strings fairly large, you are never guaranteed to receive your string in one go. In the actual app you should carefully design a certain protocol that you can rely on to check if you received the whole string and combine strings received during subsequent NSStreamEvents if necessary.

SaltyNuts