2

我正在尝试在节点 js 上使用来自 RMQ 的 protobuf 消息。protobuf 消息是使用 C#.Net 上的 protobuf-net 创建的

因此,例如 c# 对象如下所示:

    [ProtoContract]
    public class PositionOpenNotification : MessageBase
    {
    [ProtoMember(1)]
    public int PositionID { get; set; }

    [ProtoMember(2)]
    public int InstrumentID { get; set; }
    ..
    ..Down to tag 30

然后它被添加到 RMQ 中,我们在另一端使用具有相同对象的 .net 侦听器对其进行解码。

但是现在我们想从 nodejs 读取消息。为此,我在 nodejs 端使用 amqplib 和 protobuf-js。

我试图使用带有装饰器的对象来解码消息,如下所示:

import { Message, Type, Field } from "protobufjs/light"; 
 
 @Type.d("PositionOpenNotification")
 export class PositionOpenNotification extends Message<PositionOpenNotification> {
 
  @Field.d(1,"int32", "required")
  public PositionID: number;
}

像这样解码:

ch.consume(q.queue, function(msg, res) {
            try {
                if(msg.content) {
                    let decoded = PositionOpenNotification.decode( msg.content);
                    console.log(" Received %s", decoded,q.queue);
                }
              } catch (e) {
                 console.log("Error  %s ", e.message)
              }
        }

其中 ch 是 amqplib RMQ 通道。

但我总是遇到以下错误之一:

偏移 2 处的无效导线类型 7

偏移 2 处的无效导线类型 4

偏移 2 处的无效导线类型 6

超出范围的索引:237 + 10 > 237

ETC

我究竟做错了什么?

编辑:

看起来我没有考虑 MessageBase(PositionOpenNotification 继承的抽象)也是一个 ProtoContract 并且数据是用长度前缀序列化的事实。

所以最后这是有效的:

添加一个带有 PositionOpenNotification 对象的 MessageBase 对象:

@Type.d("MessageBase")
export class MessageBase extends Message<MessageBase> {

  @Field.d(108, PositionOpenNotification)
  public positionOpenNotification: PositionOpenNotification;
}

然后在反序列化它时:

 if(msg.content) {
    var reader = Reader.create(msg.content);
    let decoded = MessageBase.decodeDelimited(reader);
 }
4

1 回答 1

1

电线类型 7 不存在,因此:至少,错误是正确的。

这种类型的错误通常表明负载在传输过程中已损坏。最常见的方法是将其视为文本,和/或(非常频繁地看到的东西):通过向后编码运行它以通过文本协议传输二进制数据。检查你没有这样做。基本上,您需要在两端获得完全相同的字节;在你拥有它之前,没有其他方法可以工作。特别是,如果您需要通过文本协议传输二进制文件:base-64 是您的朋友。

附带说明:protobuf-net 具有为您的对象模型导出 .proto 模式的方法,以使 x-plat 更方便。寻找Serializer.GetProto<T>

如果您有不确定的有效负载,可以使用https://protogen.marcgravell.com/decode来验证和检查二进制数据。

于 2020-06-22T15:41:35.660 回答