objective-cprotocol-buffersmetasyntactic-variablecocoaasyncsocket

cocoaasyncsocket sending data >128bytes (google protocol buffers)


I'm using cocoaasyncsocket to send data Google Protocol Buffers (using http://code.google.com/p/metasyntactic/wiki/ProtocolBuffers) to a Java server. This is all fine BUT for messages (protoToSend) >128bytes I'm running into issues as the Java server can not read the message length correctly, I think because I'm sending the wrong length from Objective C.

I currently send the data as follows:

AsyncSocket *socket;


- (void)sendProtoToServer:(RequestMessage *)protoToSend {
     NSData *d = [protoToSend data];
     int s = [protoToSend serializedSize];

     NSData *size = [NSData dataWithBytes:&s length:1];
     [socket writeData:size withTimeout:TIME_OUT tag:100];
     [socket writeData:d withTimeout:TIME_OUT tag:101];
}

Any ideas?

Thanks in advance


Solution

  • The length is little-endian varint encoded, presumably - meaning it is in chunks of 7-bits with the MSB as a continuation bit. If the MSB is set, then you need to process the next byte (and so on) to get the combined length, then use bitwise shift to combine them.

    Indeed, for all numbers < 128, this indeed looks identical to reading a single byte.

    See here for the spec on decoding base-128 varints.