Search code examples
objective-cnsdatabonjour

NSData merged together?


I send some data over Bonjour:

NSString *songString = [NSString stringWithFormat:@"sn:%@", [bHelp song]];
NSString *artistString = [NSString stringWithFormat:@"an:%@", [bHelp artist]];
NSData *imageData = [self PNGRepresentationOfImage:[bHelp getArtwork]];
NSData *songData = [songString dataUsingEncoding:NSUTF8StringEncoding];
NSData *artistData = [artistString dataUsingEncoding:NSUTF8StringEncoding];
[self.server sendData:songData error:nil];
[self.server sendData:artistData error:nil];
[self.server sendData:imageData error:nil];

Then receive it:

NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
UIImage *image = [[UIImage alloc] initWithData:data];
if (message != nil) {
    NSLog(message);
    if ([message hasPrefix:@"sn:"]) {
        _songName = [message stringByReplacingOccurrencesOfString:@"sn:" withString:@""];
    } else if ([message hasPrefix:@"an:"]) {
        _artistName = [message stringByReplacingOccurrencesOfString:@"an:" withString:@""];
    }
    return;
}

if (image != nil) {
    self.albumImage = image;
    return;
}

But songData, artistData, and imageData are all received as one. An example would be: sn:BURN IT DOWNan:Linkin Park

If I send imageData first, it never recognizes songData and artistData. If I send imageData last, songData and artistData are mushed together and imageData is never recognized.


Solution

  • It appears you just send a series of bytes with no delimiter or indicator of the data size. If you want to send multiple chunks of data like you are, you need a way to tell where one chunk ends and the next starts.

    One common approach would be to send a length, then the data. The length would be the number of bytes and this would always be 4 or 8 bytes. This would all be handled in the sendData:error: method.

    On the receiving end you would read the 4 or 8 bytes representing the length, then you would read length bytes.

    In the end, you would send the following data:

    1. song data length
    2. song data
    3. artist data length
    4. artist data
    5. image data length
    6. image data