0

我有一个蚊子经纪人在我的电脑上运行,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();
        }
}

但它永远不会连接,因为我没有看到“已连接到代理”消息并且它卡在了 while 循环中。我究竟做错了什么?

4

1 回答 1

1

如评论中所述,如果客户端已连接,则严格的 while 循环检查是多余的,因为已经有一个onSuccess()可用于该测试的回调。

subscribe()应将调用移至回调中。

在客户端连接后处理订阅主题的最佳方法是subscribe()在检查连接状态的 if 块中对调用进行门控。如果该测试失败,则将主题添加到全局数组中,然后connect()再次调用。subscribe()回调中的应该onSuccess()使用带有主题数组的版本

于 2020-11-14T12:35:25.670 回答