Hivemq java 客户端重新连接 auth 用户名和密码不去它正在尝试使用用户名和密码重新连接

Hivemq java client on reconnect auth username and password not going it is trying to reconnect with username and password

当 wifi 关闭然后打开然后重新连接时,它不会在身份验证中发送用户名和密码,这会导致代理出现 UN_AUTHORIZED 错误。我正在使用带有 mosquitto-go-auth 的 Mosquitto。

val mqttClient = MqttClient.builder().useMqttVersion5()
            .identifier(UUID.randomUUID().toString())
            .serverHost("10.0.2.2")
            .serverPort(1883)
            .automaticReconnectWithDefaultConfig()
            .addConnectedListener {
                Log.d("MqttHelper", "addConnectedListener => $it")
            }
            .addDisconnectedListener {
                Log.d("MqttHelper", "addDisconnectedListener => ${it.cause}")
            }
            .buildAsync()
        mqttClient.connectWith().simpleAuth().username("guest").password("guest".toByteArray())
            .applySimpleAuth().send()
            .whenComplete { connAck, throwable ->
                if (throwable != null) {
                    Log.e("MqttHelper", "connect error", throwable)
                    // handle failure
                } else {
                    Log.d("MqttHelper", "Connected successfully => connAck: $connAck")
                }
            }

您仅在连接操作中设置了用户名和密码,因此它们仅用于第一次连接而不用于任何重新连接。

相反,您可以直接在客户端设置用户名和密码,如以下代码片段所示:

val mqttClient = MqttClient.builder().useMqttVersion5()
        ...
        .automaticReconnectWithDefaultConfig()
        .simpleAuth()
            .username("guest")
            .password("guest".toByteArray())
            .applySimpleAuth()
        .buildAsync()