Skip to content

Instantly share code, notes, and snippets.

@Stef3st
Created June 14, 2023 22:15
Show Gist options
  • Save Stef3st/cc9a62e94898ac03fb5e833012fd262a to your computer and use it in GitHub Desktop.
Save Stef3st/cc9a62e94898ac03fb5e833012fd262a to your computer and use it in GitHub Desktop.
Voorbeeld: Connect->Subscribe->Publish->Disconnect
package org.example;
import org.eclipse.paho.client.mqttv3.*;
public class MqttExample implements MqttCallback {
private static final String TOPIC = "l2mqtt/exampleTopic";
private static final String CONTENT = "Test message";
private static final String BROKER = "tcp://test.mosquitto.org:1883";
private static final String CLIENT_ID = "mqttExampleClient";
private static final int QOS = 0;
public void testMQTT() {
try {
MqttAsyncClient mqttClient = new MqttAsyncClient(BROKER, CLIENT_ID, null);
MqttConnectOptions mqttConnectOptions = generateMQTTConnectOptions();
mqttClient.setCallback(this);
System.out.printf("Connecting to broker: %s\n", BROKER);
IMqttToken tok = mqttClient.connect(mqttConnectOptions);
tok.waitForCompletion();
System.out.println("Connected");
System.out.printf("Subscribing to topic: %s\n", TOPIC);
mqttClient.subscribe(TOPIC, QOS);
System.out.printf("Publish message to topic: %s\n", TOPIC);
mqttClient.publish(TOPIC, CONTENT.getBytes(), QOS, false);
//Small delay to make sure the message gets caught before disconnecting.
Thread.sleep(500);
mqttClient.disconnect();
System.out.println("Disconnected");
} catch(Exception e) {
e.printStackTrace();
}
}
private static MqttConnectOptions generateMQTTConnectOptions() {
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setConnectionTimeout(30);
mqttConnectOptions.setKeepAliveInterval(60);
return mqttConnectOptions;
}
@Override
public void connectionLost(Throwable cause) {
System.out.println("Connection lost...");
}
@Override
public void messageArrived(String topic, MqttMessage message) {
try {
String msg = new String(message.getPayload());
System.out.printf("Received message from topic: %s\n", topic);
System.out.printf("Message: %s\n", msg);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Published message!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment