无法从javascript中的protobuf消息中读取字节

时间:2015-11-18 23:47:58

标签: javascript node.js protocol-buffers

我需要使用javascript在protobuf消息中对bytes进行编码/解码 如图所示,字符串工作正常,但在消息定义中使用bytes时,我可以看到数据包含在已解码的bytebuffer中(printDebug显示了这一点),但我无法提取字符串:

test.proto:

syntax = "proto3";

package Testing;

message Record {
  string  data = 1;
}

message Bytes {
  bytes data = 1;
}

TestProto.js:

var ProtoBuf = require("protobufjs");
var ByteBuffer = require("bytebuffer");

var builder = ProtoBuf.loadProtoFile('test.proto');
var Testing = builder.build('Testing');

var test = new Testing.Record();
test.data = 'Hello World';

var encoded = test.encode();
encoded.printDebug();

var unencoded = Testing.Record.decode(encoded);
console.log(unencoded.data);
// prints 'Hello World'

console.log('\n\n');

var bytes = new Testing.Bytes();
var bb = new ByteBuffer();
bb.writeIString('Testing 1,2,3');
bb.flip();
bytes.data = bb;

var bytesEncoded = bytes.encode();
bytesEncoded.printDebug();

var bytesUnencoded = Testing.Bytes.decode(bytesEncoded);
bytesUnencoded.data.printDebug();
console.log(bytesUnencoded.data.readIString());

控制台输出:

$ node TestProto.js
ByteBufferNB(offset=0,markedOffset=-1,limit=13,capacity=16)
-------------------------------------------------------------------
<0A 0B 48 65 6C 6C 6F 20 57 6F 72 6C 64>00 00 00   ..Hello.World...

Hello World



ByteBufferNB(offset=0,markedOffset=-1,limit=19,capacity=32)
-------------------------------------------------------------------
<0A 11 00 00 00 0D 54 65 73 74 69 6E 67 20 31 2C   ......Testing.1,
 32 2C 33>00 00 02 00 00 01 00 00 00 01 00 00 00   2,3.............

ByteBufferNB(offset=2,markedOffset=-1,limit=19,capacity=32)
-------------------------------------------------------------------
 0A 11<00 00 00 0D 54 65 73 74 69 6E 67 20 31 2C   ......Testing.1,
 32 2C 33>00 00 02 00 00 01 00 00 00 01 00 00 00   2,3.............

C:\node_modules\protobufjs\node_modules\bytebuffer\dist\ByteBufferNB.js:1874
            throw RangeError("Index out of bounds: "+offset+" + "+temp+" <= "+this.buffer.length);
            ^

RangeError: Index out of bounds: 6 + 218103808 <= 32
    at RangeError (native)
    at module.exports.ByteBufferPrototype.readIString (C:\node_modules\protobufjs\node_modules\bytebuffer\dist\ByteBufferNB.js:1874:19)
    at Object.<anonymous> (C:\TestProto.js:30:33)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
    at node.js:963:3

1 个答案:

答案 0 :(得分:0)

readIString解决问题之前,由bytesUnencoded.data明确地设置为Big Endian。

bytesUnencoded.data.BE();
console.log(bytesUnencoded.data.readIString());