【问题标题】:Decoding a Google protocol buffer message in javascript using ProtoBuf.js使用 ProtoBuf.js 在 javascript 中解码 Google 协议缓冲区消息
【发布时间】:2015-05-22 01:59:27
【问题描述】:

我正在尝试使用 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 文件的链接。 https://github.com/dcodeIO/ProtoBuf.js/blob/master/tests/complex.proto

谁能指出我哪里出错了?

非常感谢

【问题讨论】:

    标签: javascript protocol-buffers


    【解决方案1】:

    大概是这几行:

    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 捕获它们。

    【讨论】:

    • 非常感谢肯顿。其实我想到了这个问题。但现在面临更大的问题。我能够解码此消息,但是当我从一个由 java 客户端编码的 websocket 收到消息时,解码不起作用。有什么想法吗?非常感谢。
    • 基本上这就是我现在所面临的。 stackoverflow.com/questions/30385865/…
    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多