Java as MQTT publisher and subscriber client

Assuming you have Eclipse IDE on your laptop or computer or system. Before you start publishing or subscribing using Java , you need a Broker. Broker can be install on Windows machine or Linux machine or Raspberry pi or VM instance of Google cloud ( Installing MQTT Broker on Windows or Installing MQTT Broker on Linux or Installing MQTT Broker on Raspberry PI or Installing on VM instance of Google Cloud ) etc. In order to use java program as MQTT publisher or MQTT subscriber you need to import org.eclipse.paho.client.mqttv3-1.2.1.jar file. Steps to import jar file is given below.

1)Open your Eclipse IDE.
2)Click on File -> New -> Java Project and Enter project name in the Project name field which is shown below and click on Finish.

3)Right Click on Created java project -> New ->  click on Folder and enter Folder name as lib and click on Finish which is shown below.

4)Download the Following org.eclipse.paho.client.mqttv3-1.2.1.jar file
org.eclipse.paho.client.mqttv3-1.2.1.jar (77 downloads)
5)Copy the downloaded org.eclipse.paho.client.mqttv3-1.2.1.jar file
6)Now right click on lib folder which is created in step 3 and click on paste .
7)Now Right click on project created  in step 3 and click  on Properties which is shown below. Now click on Java Build Path -> Libraries -> Add JARs and now first expand Your project and then expand lib folder and select jar file and click on OK. Now click on Apply and then click on Apply and close.

Congrats you have Successfully Imported org.eclipse.paho.client.mqttv3-1.2.1.jar file.



Assuming you have successfully imported org.eclipse.paho.client.mqttv3-1.2.1.jar file.
Steps are given below to use java program as MQTT publisher:
1)Right click on src folder of Java project which you created in step 3 while installing org.eclipse.paho.client.mqttv3-1.2.1.jar file and select New -> Class and enter  MqttPublisher in Name field of Java Class which is shown below and click on Finish.

2)Download the below java programs and open with Notepad or Notepad++ or any text editor.
MqttPublisher.java (52 downloads)

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttPublisher {

    public static void main(String[] args) {

    	//Topic name 
        String topic        = "test";
        //data to be send
        String content      = "Temp:20,Humi:70";
        int qos             = 0;
        /*hostname is localhost as mqtt publisher and broker are
          running on the same computer*/ 
        String broker       = "tcp://localhost:1883";
        String clientId     = "JavaSample";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: "+broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected to broker");
            System.out.println("Publishing message:"+content);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            sampleClient.close();
            System.exit(0);
            } catch(MqttException me) {
            System.out.println("reason "+me.getReasonCode());
            System.out.println("msg "+me.getMessage());
            System.out.println("loc "+me.getLocalizedMessage());
            System.out.println("cause "+me.getCause());
            System.out.println("excep "+me);
            me.printStackTrace();
        }
    }
}

3)Copy the code and paste in MqttPublisher.java window which is shown below.

4)Run your MqttPublisher.java file
5)For understanding purpose, here command prompt as subscriber is taken which is subscribing to topic test

Congrats you have successfully implemented java programs as MQTT Publisher. If you want to know , how to use command prompt as publisher and subscriber please click on below link.
Command prompt as MQTT publisher and Subscriber



Assuming you have successfully imported org.eclipse.paho.client.mqttv3-1.2.1.jar file.
Steps are given below to use java program as MQTT Subscriber:
1)Right click on src folder of Java project which you created in step 3 while installing org.eclipse.paho.client.mqttv3-1.2.1.jar file and select New -> Class and enter  MqttSubscriber in Name field of Java Class which is shown below and click on Finish.

2)Download the below java programs and open with Notepad or Notepad++ or any text editor.
MqttSubscriber.java (50 downloads)

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttSubscriber implements MqttCallback  {

	/** The broker url. */
	private static final String brokerUrl ="tcp://localhost:1883";

	/** The client id. */
	private static final String clientId = "clientId";

	/** The topic. */
	private static final String topic = "test";

	public static void main(String[] args) {

		System.out.println("Subscriber running");
		new MqttSubscriber().subscribe(topic);

	}

	public void subscribe(String topic) {
		//	logger file name and pattern to log
		MemoryPersistence persistence = new MemoryPersistence();

		try
		{

			MqttClient sampleClient = new MqttClient(brokerUrl, clientId, persistence);
			MqttConnectOptions connOpts = new MqttConnectOptions();
			connOpts.setCleanSession(true);

			System.out.println("checking");
			System.out.println("Mqtt Connecting to broker: " + brokerUrl);

			sampleClient.connect(connOpts);
			System.out.println("Mqtt Connected");

			sampleClient.setCallback(this);
			sampleClient.subscribe(topic);

			System.out.println("Subscribed");
			System.out.println("Listening");

		} catch (MqttException me) {
			System.out.println(me);
		}
	}

	 //Called when the client lost the connection to the broker
	public void connectionLost(Throwable arg0) {
		
	}

	//Called when a outgoing publish is complete
	public void deliveryComplete(IMqttDeliveryToken arg0) {

	}

	public void messageArrived(String topic, MqttMessage message) throws Exception {

		System.out.println("| Topic:" + topic);
		System.out.println("| Message: " +message.toString());
		System.out.println("-------------------------------------------------");

	}

}

3)Copy the code and paste in MqttSubscriber.java window which is shown below.

4)Run your MqttSubscriber.java file
5)Congrats You have successfully implemented java Program as MQTT subscriber.

Note: If you want to test your MQTT publisher and Subscriber code then first run your MqttSubscriber.java code and then run MqttPublisher.java file which is shown below.




You may also like...

Leave a Reply