Created
January 8, 2013 02:51
-
-
Save rsattar/4480663 to your computer and use it in GitHub Desktop.
How to parse a Socket.IO payload (== packets bunched together), so that we can parse them as individual packets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sometimes Socket.IO "batches" up messages in one packet, | |
// so we have to split them. | |
// | |
- (NSArray *)packetsFromPayload:(NSString *)payload | |
{ | |
// "Batched" format is: | |
// �[packet_0 length]�[packet_0]�[packet_1 length]�[packet_1]�[packet_n length]�[packet_n] | |
if([payload hasPrefix:@"\ufffd"]) { | |
// Payload has multiple packets, split based on the '�' character | |
NSMutableArray *packets = [NSMutableArray arrayWithCapacity:2]; | |
// Skip the first character, then split | |
NSArray *split = [[payload substringFromIndex:1] componentsSeparatedByString:@"\ufffd"]; | |
// Now all of the odd-numbered indices are the packets (1, 3, 5, etc.) | |
for (NSInteger i=0; i<split.count; i++) { | |
if (i % 2 != 0) { | |
[packets addObject:split[i]]; | |
} | |
} | |
NSLog(@"Parsed a payload!"); | |
return packets; | |
} else { | |
// Regular single-packet payload | |
return @[payload]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment