2013-10-25 31 views
0

我一直想用這個項目Axon與iOS應用程序通過tcp連接進行連接實驗。朝該文檔的端部的協議被解釋爲這樣構建位掩碼?按位數據包

導線協議是簡單和非常zeromq狀,其中是表示大致〜16MB的最大長度爲24位無符號整數。數據字節當前僅用於存儲編解碼器,例如「json」僅爲1,接着通過選擇相同的編解碼器,客戶端接收到的JSON消息將自動解碼。

隨着圖

octet:  0  1  2  3  <length> 
     +------+------+------+------+------------------... 
     | meta | <length>   | data ... 
     +------+------+------+------+------------------... 

我都有這樣的經驗與二進制協議創建數據包如工作:

NSUInteger INT_32_LENGTH = sizeof(uint32_t); 

uint32_t length = [data length]; // data is an NSData object 

NSMutableData *packetData = [NSMutableData dataWithCapacity:length + (INT_32_LENGTH * 2)]; 
[packetData appendBytes:&requestType length:INT_32_LENGTH]; 
[packetData appendBytes:&length length:INT_32_LENGTH];     
[packetData appendData:data];           

所以我的問題是如何將您創建的數據包Axon的要求,我會假設一些轉變,我不太瞭解。

回答

0

分配1個大小爲char的字符或無符號字符數組== == packet_size; Decalre常數:

const int metaFieldPos = 0; 
const int sizeofMetaField = sizeof(char); 
const int lengthPos = metaFieldPos + sizeofMetaField; 
const int sizeofLengthField = sizeof(char) * 3; 
const int dataPos = lengthPos + sizeofLengthField; 

如果你得到的數據,並可以識別數據包的開始時,你可以通過指針使用常量以上 導航。

可能是這些功能將幫助你(他們使用Qt,但你可以很容易地把它們翻譯成庫,您使用)

quint32 Convert::uint32_to_uint24(const quint32 value){ 
    return value & (quint32)(0x00FFFFFFu); 
} 

qint32 Convert::int32_to_uint24(const qint32 value){ 
    return value & (qint32)(0x00FFFFFF); 
} 

quint32 Convert::bytes_to_uint24(const char* from){ 
    quint32 result = 0; 
    quint8 shift = 0; 
    for (int i = 0; i < bytesIn24Bits; i++) { 
     result |= static_cast<quint32>(*reinterpret_cast<const quint8 *>(from + i)) << shift; 
     shift+=bitsInByte; 
    } 
    return result; 
} 

void Convert::uint32_to_uint24Bytes(const quint32 value, char* from){ 
    quint8 shift = 0; 
    for (int i = 0; i < bytesIn24Bits; i++) { 
     const quint32 buf = (value >> shift) & 0xFFu; 
     *(from + i) = *reinterpret_cast<const char *>(&buf); 
     shift+=bitsInByte; 
    } 
} 

QByteArray Convert::uint32_to_uint24QByteArray (const quint32 value){ 
    QByteArray bytes; 
    bytes.resize(sizeof(value)); 
    *reinterpret_cast<quint32 *>(bytes.data()) = value; 
    bytes.chop(1); 
    return bytes; 
}