import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttCallback;
public class MqttPushClient {
private static final String HOST = "tcp://iot.eclipse.org:1883";
private static final String CLIENTID = "MyClientID";
private MqttClient client;
public MqttPushClient() {
try {
client = new MqttClient(HOST, CLIENTID);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName("username");
options.setPassword("password".toCharArray());
options.setCleanSession(true);
System.out.println("Connecting to broker: " + HOST);
client.connect(options);
client.setCallback(new MqttCallback() {
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message arrived: " + new String(message.getPayload()));
}
public void connectionLost(Throwable cause) {
System.out.println("Connection lost");
}
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("Delivery complete");
}
});
System.out.println("Connected");
} catch (Exception e) {
e.printStackTrace();
}
}
public void subscribe(String topic) {
try {
client.subscribe(topic);
System.out.println("Subscribed to topic: " + topic);
} catch (Exception e) {
e.printStackTrace();
}
}
public void publish(String topic, String content) {
try {
MqttMessage message = new MqttMessage(content.getBytes());
MqttDeliveryToken token = client.publish(topic, message);
token.waitForCompletion();
System.out.println("Message published");
} catch (Exception e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
client.disconnect();
System.out.println("Disconnected");
client.close();
} catch (Exception e) {
评论已关闭