我使用库paho与mqtt代理连接,发送消息,几乎一切正常,但我有setTimeToWait()方法的问题。它不会在方法setTimeToWait(2000)或setTimeToWait(10)中输入多少毫秒。我总是收到来自publiusher的消息。
为什么我可以在几小时内收到消息?如果我将等待时间设置为2000毫秒。我认为在发布者没有收到消息后2秒我的订阅者无法从发布者处收到消息,并且将返回控制权。
我做错了什么?
发布商代码:
public class MqttPublishSample {
public static void main(String[] args) throws MqttException {
String messageString = "{\"device_status\": \"ready\"}";
if (
args.length == 2 ) {
messageString = args[1];
}
System.out.println("== START PUBLISHER ==");
MqttClient client = new MqttClient("tcp://localhost:1883" , MqttClient.generateClientId());
client.connect();
MqttMessage message = new MqttMessage();
message.setPayload(messageString.getBytes());
message.setQos(1);
client.publish("/catalog", message);
System.out.println("\tMessage '"+ messageString +"' to 'iot_data'");
client.disconnect();
System.out.println("== END PUBLISHER ==");
}
}
订阅者代码:
public class MqttSuscribeSample {
public static void main(String[] args) {
System.out.println("== START SUBSCRIBER ==");
try{
MqttClient client=new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
client.setTimeToWait(2000);
client.setCallback( new SimpleMqttCallback() );
client.connect();
client.subscribe( "/catalog");
}catch (Exception ex){
ex.printStackTrace();
}
}
}
SimpleMqttCallback代码
public class SimpleMqttCallback implements MqttCallback {
public void connectionLost(Throwable throwable) {
System.out.println("Connection to MQTT broker lost!");
}
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
System.out.println("Message received:\t"+ new String(mqttMessage.getPayload()) );
}
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
}
答案 0 :(得分:0)
setTimeToWait()
方法是客户端在执行特定操作时应等待代理响应的时间,例如。
客户端应该等待多长时间或者为现有订阅传递消息。
如果您想要这种行为,您需要运行自己的计时器并取消订阅主题,或者在代理超时时与代理断开连接。