【问题标题】:ProtoBuf Message Over Mqtt subcriber issueProtoBuf Message Over Mqtt 订阅者问题
【发布时间】:2020-01-13 03:31:07
【问题描述】:

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

所以首先我在将我的值设置为 protobuf 格式之后创建协议缓冲区格式(它的谷歌格式,如 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");

【问题讨论】:

    标签: java spring protocol-buffers mqtt


    【解决方案1】:

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

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

    类似这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      相关资源
      最近更新 更多