receive mqtt mess on ubuntu server

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
1
Indexable
Never
<dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.2.5</version>
</dependency>

String broker = "tcp://mqtt.eclipseprojects.io:1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();

MqttClient client = new MqttClient(broker, clientId, persistence);

MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);

System.out.println("Connecting to broker: " + broker);
client.connect(connOpts);
System.out.println("Connected");

String topic = "MQTT Examples";
int qos = 2;

System.out.println("Subscribing to topic: " + topic);
client.subscribe(topic, qos);
System.out.println("Subscribed");

client.setCallback(new MqttCallback() {
    public void connectionLost(Throwable cause) {
        System.out.println("Connection lost: " + cause.getMessage());
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println("Message received: " + new String(message.getPayload()));
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("Delivery complete");
    }
});

client.disconnect();
System.out.println("Disconnected");