使用 ProtoBuf.js 在 javascript 中解码 Google 协议缓冲区消息

Decoding a Google protocol buffer message in javascript using ProtoBuf.js

我正在尝试使用 javascript (ProtoBuf.js)

中的 google 协议缓冲区通过 MQTT 发送消息

我能够使用以下代码对消息进行编码:

var ProtoBuf = dcodeIO.ProtoBuf;
var builder = ProtoBuf.loadProtoFile("./complex.proto"),
Game = builder.build("Game"),
Car = Game.Cars.Car;
var car = new Car({
"model" : "Rusty",
"vendor" : {
            "name" : "Iron Inc.",
           "address" : {
                "country" : "USa"
             }
          },
    "speed" : "FAST"
 });
 var buffer = car.encode();
console.log(buffer);
var messagegpb = buffer.toBuffer();
console.log(messagegpb ); //This prints "ArrayBuffer { byteLength: 29 }"

当我尝试以下操作时进行解码,但它什么也没做。我在浏览器中也看不到任何日志。

var dec = builder.build("Game"); //nothing after this line gets executed
var msg = dec.decode(messagegpb);
console.log(msg);

这是我正在使用的 .proto 文件的 link。 https://github.com/dcodeIO/ProtoBuf.js/blob/master/tests/complex.proto

有人能指出我哪里出错了吗?

非常感谢

大概是这些行:

var dec = builder.build("Game");
var msg = dec.decode(messagegpb);

需要:

var Game = builder.build("Game");
var msg = Game.Cars.Car.decode(messagegpb);

也就是说,您需要指定要解码的类型。

可能是您尝试调用 dec.decode 时引发异常,提示 decode 方法不存在。您应该已经能够在错误控制台上看到这些异常,或者使用 try/catch.

捕获它们