Search code examples
javamqtthivemq

How to properly use a SSL configuration in HiveMQ Client? (MQTT)


I created a client to test using a secure connection and encrypted payload so I wanted to use the default SSL configuration. I tried to do this but I got a ConnectionClosedException and the server immediately closely. Should I be configuring something on the server? I left code and the exception down below.

HiveMQ:

https://github.com/hivemq/hivemq-community-edition https://github.com/hivemq/hivemq-mqtt-client

Code:

    // Creates the client object using Blocking API 

     subscriber = Mqtt5Client.builder()
    .identifier(UUID.randomUUID().toString()) // the unique identifier of the MQTT client. The ID is randomly generated between 
    .serverHost("localhost")  // the host name or IP address of the MQTT server. Kept it localhost for testing. localhost is default if not specified.
    .serverPort(1883)  // specifies the port of the server
    .addConnectedListener(context -> ClientConnectionRetreiver.printConnected("Subscriber1"))        // prints a string that the client is connected
    .addDisconnectedListener(context -> ClientConnectionRetreiver.printDisconnected("Subscriber1"))  // prints a string that the client is disconnected
    .sslWithDefaultConfig()
    .buildBlocking();  // creates the client builder                
     subscriber.connect();

Exception:

com.hivemq.client.mqtt.exceptions.ConnectionClosedException: Server closed connection without DISCONNECT.
at com.hivemq.client.internal.mqtt.MqttBlockingClient.connect(MqttBlockingClient.java:91)
at com.hivemq.client.mqtt.mqtt5.Mqtt5BlockingClient.connect(Mqtt5BlockingClient.java:64)
at com.main.SubThread.run(SubThread.java:71)
at java.base/java.lang.Thread.run(Thread.java:834)

Solution

  • In order to use Ssl communications I needed to set up the HiveMQ server to speak TLS. The server does not come pre configured and must be done manually. I followed this link:

    https://github.com/hivemq/hivemq-community-edition/wiki/HowTos#howto-configure-server-side-tls-with-hivemq-and-keytool-self-signed