开发者

iPhone SDK send string over wifi

开发者 https://www.devze.com 2023-01-04 01:07 出处:网络
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 ca

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 pointe开发者_StackOverflowrs 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: How to add data for NSOutputStream? but that did not fully help either.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消