Search code examples
javamqtthivemq

HiveMQ Mqtt Client


I am trying to connect to our local MQTT broker.

I create client:

Mqtt5AsyncClient client = Mqtt5Client.builder()
            .serverHost(connectionConfig.getIp())
            .serverPort(1883)
            .automaticReconnectWithDefaultConfig()
            .identifier(connectionConfig.getClientID())
            .addConnectedListener(context ->  isConnected = true)
            .addDisconnectedListener(context -> isConnected = false)
            .buildAsync();

and latter I try to open connection:

private void openConnection()
    {
        logger.info("openConnection() start");
        client.connectWith()
                .simpleAuth()
                .username(connectionConfig.getUser())
                .password(connectionConfig.getPassword().getBytes())
                .applySimpleAuth()
                .send()
                .whenComplete((connAck, throwable) ->
                {
                    if (throwable != null)
                    {
                        logger.error("connect error");
                        logger.error("couldn't connect to broker={}", throwable);
                    } else
                    {
                        logger.info("mqtt client connected");
                        subscribe();
                    }

                });
        logger.info("openConnection() end");
    }

I am waiting for whenComplete to give me some result but nothing happens. In log I only get this:

13:00:53.375 [Thread-0] INFO  mqtt.MqttHiveClient - openConnection() start
13:00:55.582 [Thread-0] INFO  mqtt.MqttHiveClient - openConnection() end

Should I catch Exceptions somehow different?

Even if i change:

.serverHost(connectionConfig.getIp())

to something wrong:

.serverHost("asdž)

nothing is thrown.


Solution

  • I removed the line:

    .automaticReconnectWithDefaultConfig()
    

    and I now get the exception thrown when trying to connect. It looks that if you have automaticReconnect enabled it tries to reconnect without throwing exception.

    Reason why it was failing to connect was that I was using tcp://127.0.0.1 instead of just 127.0.0.1.