【问题标题】:MqttAndroidClient not able to connect to mosquittoMqttAndroidClient 无法连接到 mosquitto
【发布时间】:2020-11-14 10:38:55
【问题描述】:

我的计算机上运行着一个带有 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 循环中。我做错了什么?

【问题讨论】:

  • 将订阅代码移动到onSuccess() 回调中。那个紧的while循环只会最大化CPU
  • 好的,但是如果我想马上订阅另一个主题怎么办?

标签: java android mqtt mosquitto paho


【解决方案1】:

正如 cmets 中所述,检查客户端是否已连接的紧密 while 循环是多余的,因为已经有一个回调 onSuccess() 可用于该测试。

subscribe() 的调用应该移到回调中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-25
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多