这是我的最终工作代码:
没有这条线,
client.setCallback(new SimpleMqttCallBack());
我无法打印消息。不知道为什么?
package com.mapr.demo.mqtt.simple;
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;
public class Subscriber {
// private static final String CONNECTION_URL = "tcp://localhost:1883";
private static final String CONNECTION_URL = "tcp://192.168.1.102:1883";
private static final String SUBSCRIPTION = "Area1/#";
private static final String USERNAME = "username";
private static final String PASSWORD = "top-secret";
public static void main(String[] args) throws MqttException {
System.out.println("== START SUBSCRIBER ==");
MqttClient client = new MqttClient(CONNECTION_URL, MqttClient.generateClientId());
MqttConnectOptions connOpts = setUpConnectionOptions(USERNAME, PASSWORD);
// This callback is required to receive the message
client.setCallback(new SimpleMqttCallBack());
client.connect(connOpts);
client.subscribe(SUBSCRIPTION);
}
public void messageArrived(String topic, MqttMessage message) throws MqttException {
System.out.println(String.format("[%s] %s", topic, new String(message.getPayload())));
System.out.println("\tMessage published on topic 'Area1'");
}
private static MqttConnectOptions setUpConnectionOptions(String username, String password) {
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setUserName(username);
connOpts.setPassword(password.toCharArray());
return connOpts;
}
}