我正在使用Mosquitto作为经纪人发布关于“测试”主题的消息。 当我运行订户代码以检索消息并在同一网络上的其他设备上显示消息时,消息未显示。我在托管Broker的设备上使用命令“sudo mosquitto_sub -h 192.168.43.17 ......”检查了消息是否正在发布。 并且消息已由设备发布并成功检索并显示。 订户代码是
package chat;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MQTTSubscriber implements MqttCallback{
public MQTTSubscriber(){}
public void do1(){
String topic= "Test";
String broker= "tcp://192.168.43.17:1883";
int qos=1;
String clientId="20130326";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: "+broker);
sampleClient.setCallback(this);
sampleClient.connect(connOpts);
System.out.println("Connected");
sampleClient.subscribe(topic, qos);
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch(MqttException me) {
System.out.println("reason "+me.getReasonCode());
System.out.println("msg "+me.getMessage());
System.out.println("loc "+me.getLocalizedMessage());
System.out.println("cause "+me.getCause());
System.out.println("excep "+me);
me.printStackTrace();
}
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("Message Arrived: " + message);
}
public void connectionLost(Throwable arg0) {
System.out.println("Connection lost");
}
public void deliveryComplete(IMqttDeliveryToken arg0) {
System.out.println("Delivery done");
}
public static void main(String args[]){
new MQTTSubscriber().do1();
}
}
根据我的理解,任何三个函数messageArrived(),deilveryComplete()和connectionLost()都没有被调用。我应该在代码中进行哪些更改才能显示消息?
答案 0 :(得分:0)
一旦连接到代理,您就会断开连接并退出,因此客户端永远没有时间接收任何消息。
删除以下代码行:
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);