Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
final Mqtt5AsyncClient client = Mqtt5Client.builder()
                .serverHost("localhost")
                .identifier("client1")
                .sslConfig()
                .protocols(Arrays.asList("TLSv1.2"))
                .keyManagerFactory(kmf)
                .trustManagerFactory(tmf)
                .applySslConfig()
                .serverPort(8883)
                .buildAsync();

...

Code Block
2020-04-03 11:01:33,701 - Client ID: hmq_vJdLo_4_0a462bee1ad8693e9fd676f62f0f8af9client1, IP: 127.0.0.1, Clean Start: true, Session Expiry: 0 connected.

Note

This is guide only presents a minimal code example and not ready for use in production environments

Expand
titleEntire code sample

Code Block
public class HiveMQClient {
    public static void main(String[] args) throws Exception {
        final String pathToJKS = "/path/to/keystores/client1-keystore.jks";
        final String pathToJKSTrustStore = "/path/to/keystores/client1-truststore.jks";

        //Create key store
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        final InputStream inKey = new FileInputStream(pathToJKS);
        keyStore.load(inKey, "secret".toCharArray());
    
        final Certificate certificate = keyStore.getCertificate("mqtt-client");

        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "secret".toCharArray());

        //Create trust store
        final KeyStore trustStore = KeyStore.getInstance("JKS");
        final InputStream in = new FileInputStream(pathToJKSTrustStore);
        trustStore.load(in, "secret".toCharArray());
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);

        // Build SSL context
        final SSLContext sslCtx = SSLContext.getInstance("TLSv1.2");
        sslCtx.init(null, tmf.getTrustManagers(), null);

        final List<Mqtt5Publish> message = Collections.synchronizedList(new ArrayList<>());
        final Mqtt5AsyncClient client = Mqtt5Client.builder()
                .serverHost("localhost")
                .sslConfig()
				.identifier("client1")
                .protocols(Arrays.asList("TLSv1.2"))
                .keyManagerFactory(kmf)
                .trustManagerFactory(tmf)
                .applySslConfig()
                .serverPort(8883)
                .buildAsync();

       client.connect().get();
    }
}