从C#向Python发送Protobuf消息

时间:2019-05-03 00:03:13

标签: c# python-3.x protocol-buffers netmq

我有一个简单的类,在proto文件中有两个字段:(proto3)

enum MaestroMsgType
{
    EVAL = 0;
    GET_ACK = 1;
    GET_AN = 2;
}

message MaestroMsg
{
    MaestroMsgType msgType = 1;
    string maestroMsg = 2;
}

我正在尝试使用netMQ将类形式的C#发送给python(但不太重要)。但是在python中,当尝试将数据恢复为类格式时,它将失败。

使用C#发送:

  MaestroMsg maestroMsg = new MaestroMsg
  {
       MaestroMsg_ = "someMessage",
       MsgType = MaestroMsgType.GET_AN,
   };
   string messageToSend = maestroMsg.ToString();
   NetMQMessage msg = new NetMQMessage();
   msg.Append(messageToSend);
   _pubSocket.SendMultipartMessage(msg);

python中接收消息的代码:

 received_message = sub_socket.recv_multipart()
 maestroMsg_object = MaestroMsg()
 maestroMsg_object.ParseFromString(received_message.encode())

我收到此错误消息:

 google.protobuf.message.DecodeError: Error parsing message

我不知道我在做什么错。 感谢您的回答。

1 个答案:

答案 0 :(得分:1)

因此,感谢@MarcGravell,答案是对API的错误使用:

C#:

MaestroMsg maestroMsg = new MaestroMsg
{
    MaestroMsg_ = maestroMsgStr,
    MsgType = maestroMsgType,
};

var messageToSend = maestroMsg.ToByteArray();
NetMQMessage msg = new NetMQMessage();
msg.Append(messageToSend);

_pubSocket.SendMultipartMessage(msg);

python:

received_message = sub_socket.recv_multipart()
meastro_object = MaestroMsg()
meastro_object.ParseFromString(received_message)