如何在MQTT协议中设置protobuf格式

时间:2016-04-05 09:33:41

标签: java protocol-buffers mqtt

我正在尝试通过protobuf定义我的mqtt数据包结构我使用protobuf实现了以下代码用于发布消息

代码:

 package com.cupola.demo;

 import org.eclipse.paho.client.mqttv3.MqttClient;
 import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
 import org.eclipse.paho.client.mqttv3.MqttException;
 import org.eclipse.paho.client.mqttv3.MqttMessage;
 import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class Publish {

public static void main(String[] args) {

    Sample sas = new Sample();
    String topic = "Cupola";
    String content = sas.passMessage(24,"Noor");
    int qos = 2;
    String broker = "tcp://localhost:1883";
    String clientId = "DemoPublish";
    MemoryPersistence persistence = new MemoryPersistence();

    try {
        MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        System.out.println("Connecting to broker: " + broker);
        sampleClient.connect(connOpts);
        System.out.println("Connected");
        System.out.println("Publishing message: " + content);
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        System.out.println("Message published");
        sampleClient.disconnect();
        System.out.println("Disconnected");
//            System.exit(0);
        }
        catch (MqttException me) {
        System.out.println("reason " + me.getReasonCode());
        System.out.println("msg " + me.getMessage());
        System.out.println("loc " + me.getLocalizedMessage());
        System.out.println("cause " + me.getCause());
        System.out.println("excep " + me);
        me.printStackTrace();
    }
}

}

这是设置值,通过从Publisher调用函数并根据proto文件设置值

package com.cupola.demo;

import com.cupola.demo.CatProto.Cat;

public class Sample {

public String  passMessage(int age,String name) {

    // creating the cat
    Cat noor= CatProto.Cat.newBuilder()
            .setAge(age)
            .setName(name) 
            .build();
    String message=noor.toString();


    return message;
}

}

这是我的Cat.proto文件:

option java_outer_classname="CatProto";

message Cat {
optional int32 age = 1;
required string name = 2;
}

是对还是我需要改变方式。请建议我。提前感谢你。

1 个答案:

答案 0 :(得分:3)

假设您使用了Google Protobuff库,那么您希望在toByteArray()方法中使用toString()而不是passMessage()

public byte[]  passMessage(int age,String name) {

    // creating the cat
    Cat noor= CatProto.Cat.newBuilder()
            .setAge(age)
            .setName(name) 
            .build();
    byte message[] = noor.toByteArray();


    return message;
}