Offline Message Buffering

Hello @ALX ,

Please see the example below of the client demonstrating offline message buffering.

Dependencies:

dependencies {
    implementation("com.hivemq:hivemq-mqtt-client:1.3.0")
    implementation 'io.netty:netty-handler:4.1.77.Final'
}

Java class:

import com.hivemq.client.internal.mqtt.MqttClientConnectionConfig;
import com.hivemq.client.mqtt.datatypes.MqttQos;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client;

import java.nio.charset.StandardCharsets;

public class OfflineMessageBuffering {

    public static void main(String[] args) {
        Mqtt5AsyncClient mqtt5AsyncClient = Mqtt5Client.builder()
                .serverPort(1883)
                .serverHost("broker.hivemq.com")
                .identifier("Test-client-123412")
                .automaticReconnectWithDefaultConfig()
                .buildAsync();
        mqtt5AsyncClient.toBlocking().connectWith().noSessionExpiry().send();
        // kill the channel to force a disconnect without disconnecting
        final MqttClientConnectionConfig config = (MqttClientConnectionConfig) mqtt5AsyncClient.getConfig().getConnectionConfig().get();
        config.getChannel().close();
        System.out.println("Forced a disconnection");

        mqtt5AsyncClient.subscribeWith().topicFilter("test1234")
                .callback(mqtt5Publish -> System.out.println(new String(mqtt5Publish.getPayloadAsBytes())))
                .send()
                .thenAccept(subAck -> System.out.println("Actually subscribed now"));
        System.out.println("Submitted subscribe to client");

        mqtt5AsyncClient.publishWith()
                .topic("test1234")
                .qos(MqttQos.AT_LEAST_ONCE)
                .payload("this publish will be buffered".getBytes(StandardCharsets.UTF_8))
                .send()
                .thenAccept(subAck -> System.out.println("Actually published now"));
        System.out.println("Submitted publish to client");
    }
}

If you have further questions please do not hesitate to ask.

Kind regards,
Dasha from HiveMQ team

1 Like