Created
August 21, 2018 08:31
-
-
Save suru-dissanaike/56f4f76d611db41a8b7736d316ada119 to your computer and use it in GitHub Desktop.
Simple MQTT subscribe example using the Eclipse Paho Java Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.IMqttDeliveryToken; | |
import org.eclipse.paho.client.mqttv3.MqttCallback; | |
public class HelloMQTT implements MqttCallback { | |
MqttClient client; | |
private MqttConnectOptions conOpt; | |
private static final String SERVER_URI = "tcp://broker.hivemq.com:1883"; | |
private static final String MQTT_CLIENT_PASSWORD = "TBD"; | |
private static final String MQTT_CLIENT_USERNAME = "TBD"; | |
public HelloMQTT() { | |
} | |
public static void main(String[] args) { | |
new HelloMQTT().init(); | |
} | |
public void init() { | |
System.out.println("HelloMQTT Demo"); | |
String id = client.generateClientId(); | |
try { | |
client = new MqttClient(SERVER_URI, id); | |
conOpt = new MqttConnectOptions(); | |
conOpt.setCleanSession(true); | |
conOpt.setKeepAliveInterval(15); | |
conOpt = new MqttConnectOptions(); | |
conOpt.setUserName(MQTT_CLIENT_USERNAME); | |
conOpt.setPassword(MQTT_CLIENT_PASSWORD.toCharArray()); | |
client.connect(conOpt); | |
client.setCallback(this); | |
client.subscribe("#"); // Wildcard all topics | |
} catch (MqttException e) { | |
e.printStackTrace(); | |
} | |
} | |
@Override | |
public void connectionLost(Throwable cause) { | |
// TODO Auto-generated method stub | |
} | |
@Override | |
public void messageArrived(String topic, MqttMessage message) throws Exception { | |
System.out.println(topic +" " + message); | |
} | |
@Override | |
public void deliveryComplete(IMqttDeliveryToken token) { | |
// TODO Auto-generated method stub | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment