Skip to content

Instantly share code, notes, and snippets.

@rsattar
Created January 8, 2013 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsattar/4480663 to your computer and use it in GitHub Desktop.
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.
// 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