我正在使用paho订阅mqtt主题“$ SYS /#”,以便查看客户端的连接。
我在本主题中实现了MqttCallback接口以接收消息发送,目前我只想在控制台中显示消息内容。
我的问题是无休止地接收消息,“messageArrived”函数每秒调用一次,并且始终具有相同的客户端名称。
import android.app.Activity;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
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.persist.MemoryPersistence;
public class MainActivity extends Activity {
private static final String MQTT_DIR = "/home/persistence.log";
private static final String MQTT_URI = "tcp://x.x.x.x:1883";
private MqttClient client;
private String clientId = "AndroidClient";
private String clientName = "usermqtt";
private char[] password = {'x', 'x', 'x'};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MemoryPersistence persistence = new MemoryPersistence();
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(clientName);
options.setPassword(password);
try {
client = new MqttClient(MQTT_URI, clientId, persistence);
client.connect(options);
client.subscribe("$SYS/#");
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String arg0, MqttMessage arg1)
throws Exception {
// TODO Auto-generated method stub
System.out.println("Message Received");
System.out.println(arg0);
System.out.println(arg1.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}