ProtoBuf Message Over Mqtt subcriber issue



我尝试使用 mqtt proto 发送有效负载消息,该消息以字节格式传输数据。

所以首先我在将我的值设置为 protobuf 格式后创建协议缓冲区格式(它的 Google 格式,如 json 或 xml(,然后我需要将对象转换为字节,以便通过 mqtt 协议发布,我成功地做到了

当我订阅主题并以 btye 数组格式获取有效负载时,该问题面临 不是我转换回 protobuf 或 JSON 格式 我在转换数据时遇到问题

这是我使用 Protobuf 格式发布我的消息

@Override
public void publishMessage(String topic, String message) {

Account account=        Account.newBuilder().setId(1).setCustomerId(1).setNumber("111111").build()

try {
System.out.println(Account.toByteArray());
MqttMessage mqttmessage = new MqttMessage(Account.toByteArray());
mqttmessage.setQos(this.qos);
this.mqttClient.publish(topic, mqttmessage);
} catch (MqttException me) {
logger.error("ERROR", me);
}
}

我的订阅者,我可以在其中接收我的消息/有效负载

@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// TODO Auto-generated method stub
String time = new Timestamp(System.currentTimeMillis()).toString();
System.out.println();
System.out.println("***********************************************************************");
System.out.println("Message Arrived at Time: " + time + "  Topic: " + topic + "  Message: "
+ new String(message.getPayload()));
System.out.println("***********************************************************************");

// String printToString = new JsonFormat().printToString(message.getPayload())
System.out.println("I am waitign");
}

输出我像这样

***********************************************************************
Message Arrived at Time: 2019-09-11 14:57:25.159  Topic: demoTopic2017  Message: 
bin122001��
System.out.println("I am waitign");

您正在发布 protobuf 消息,但您发布的用于处理传入消息的代码您正在尝试将其直接转换为 JSON 对象。

你不能只是将 protobuf 的原始字节转换为字符串,然后尝试将其解析为 JSON,您需要先将其解压缩为 protobuf 消息,然后您可以考虑将其转换为其他内容。

像这样:

Account act = Account.parseFrom(message.getPayload())

最新更新