MQTT simple example in java

Posted By :Shivani Chaudhary |30th October 2019

Here, we have SimpleMqttDemo java class we publish for a topic that is "data" and subscribe for the same topic and get published message after subscribing on topic.

public class SimpleMqttDemo {

    private MqttConnectOptions setUpConnectionOptions(String username, String password) {
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setAutomaticReconnect(true);
        connOpts.getMqttVersion();
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        return connOpts;
      }

    private MqttClient void mqttClientConnection() {
        MqttClient client = null;
        try {
            client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
            MqttConnectOptions connOpts = setUpConnectionOptions("shivani","shivani123")
            client.connect(connOpts);
                   System.out.println("********** Client connection established with MQTT broker **************");
        } catch (MqttException e) {
            System.out.println("client connection error"));
            e.printStackTrace();
        }
        return client;
    }

    private void publishMessage(MqttClient client) {
        try {
            MqttMessage message = new MqttMessage();
            message.setQos(2);
            String payload = "publishing test"
            message.setPayload(payload.getBytes());
            client.publish("data", message);
            System.out.println("\t Message send : '" + payload.toString() + "' to '" + "data");
            client.disconnect();
        } catch (MqttException e) {
            System.out.println("publishing error");
            e.printStackTrace();
        }
     }

    public void publish() {
    System.out.println(" Start Publisher ");
    MqttClient client = mqttClientConnection();
    publishMessage(client);
    System.out.println(" Stop Publisher ");

    }   


    public void subscribe() {

    System.out.println(" Start Subscriber (Broker) ");
    try {
    MqttClient client = mqttClientConnection();
    client.setCallback(new MqttCallBack(){

        @Overide
        public void connectionLost(Throwable throwable) {
            System.out.println("connection lost");
        }

        @Overide
        public void messageArrived(String s, MqttMessage mqttMessage) {
            System.out.println(" Message received : \t" + new String(mqttMessage.getPayload()));
        }

        @Overide
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            // Not used here
        }
    });

    } catch (MqttException e) {
    System.out.println("client connection error");
    e.printStackTrace();
    }

        if (client != null) {
            try {
                client.subscribe("data");
            } catch (MqttException e) {
                System.out.println("subscriber error");
                e.printStackTrace();
            }
        } else {
            System.out.println("topic error");
        }

    }


    public static void main(String[] args) {
    SimpleMqttDemo obj = new SimpleMqttDemo();
    obj.publish();
        obj.subscribe();
    }
 

The output will be: 

Start Publisher

********** Client connection established with MQTT broker **************

Message send: publishing test  to  data

Stop Publisher

Start Subscriber (Broker)

********** Client connection established with MQTT broker **************

Message received: publishing test

 

 

Thanks.


About Author

Shivani Chaudhary

Shivani is a quick learner, self problem-solving, quickly grasp new things and hard-working Java Developer. She has good knowledge about Java, Spring MVC, Spring boot, Spring Data JPA, Hibernate, REST Web Services. Her hobbies are travelling and learning

Request For Proposal

Sending message..

Ready to innovate ? Let's get in touch

Chat With Us