mqttandroidclient无法连接到mosquitto

l3zydbqr  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(305)

我的电脑上有一个mosquitto经纪人 mosquitto -v 我正在尝试从我的android应用程序连接到它。我正在做的是

public void connect() {
        mqttAndroidClient = new MqttAndroidClient(context, "mqtt://192.168.1.198:1883", clientId);
        mqttAndroidClient.setCallback(callback);

        mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);

        mqttAndroidClient.connect(mqttConnectOptions, context, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    Log.i(LOG_TAG, "Connected to the broker");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.e(LOG_TAG, "Not able to connect to the broker");
                }
        });

        while(!mqttAndroidClient.isConnected()) {}
        try {
            mqttAndroidClient.subscribe("notify/new", 0);
        } catch (MqttException ex) {
            System.err.println("Exception whilst subscribing");
            ex.printStackTrace();
        }
}

但它从不连接,因为我看不到“connectedtothebroker”消息,它被卡在while循环中。我做错什么了?

u0sqgete

u0sqgete1#

正如注解中所述,检查客户机是否已连接的严密while循环是多余的,因为已经存在回调 onSuccess() 可以用来做测试的。
呼叫 subscribe() 应该移到回调中。
在客户端连接后处理订阅主题的最佳方法是将调用门设置为 subscribe() 在检查连接状态的if块中。如果测试失败,则将主题添加到全局数组中,并调用 connect() 再一次。这个 subscribe()onSuccess() 回调应该使用接受主题数组的版本

相关问题