Connect to MQTT using Java SDK

**

Connect to MQTT using Java SDK

**
Eclipse Paho Java Client is an MQTT client library (MQTT Java Client) written in Java and can be used on JVM or other Java-compatible platforms (such as Android).

Eclipse Paho Java Client provides MqttAsyncClient and MqttClient asynchronous and synchronous APIs.

Install Paho Java through Maven
The Paho Java client library can be easily installed through the package management tool Maven. The latest version installed so far is as follows:

<dependency>
  <groupId>org.eclipse.paho</groupId>
	<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
	<version>1.2.2</version>
</dependency> 

Paho Java Usage Example In the Java system, Paho Java is a relatively stable and widely used MQTT client library. This example includes Paho Java in Java
language to connect to EMQX Broker and send messages. Send and receive complete codes:

App.java

    package io.emqx;
    
    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 App {
    
    
        public static void main(String[] args) {
    
    
            String subTopic = "testtopic/#";
            String pubTopic = "testtopic/1";
            String content = "Hello World";
            int qos = 2;
            String broker = "tcp://broker.emqx.io:1883";
            String clientId = "emqx_test";
            MemoryPersistence persistence = new MemoryPersistence();
    
            try {
    
    
                MqttClient client = new MqttClient(broker, clientId, persistence);
    
                // MQTT 连接选项
                MqttConnectOptions connOpts = new MqttConnectOptions();
                connOpts.setUserName("emqx_test");
                connOpts.setPassword("emqx_test_password".toCharArray());
                // 保留会话
                connOpts.setCleanSession(true);
    
                // 设置回调
                client.setCallback(new PushCallback());
    
                // 建立连接
                System.out.println("Connecting to broker: " + broker);
                client.connect(connOpts);
    
                System.out.println("Connected");
                System.out.println("Publishing message: " + content);
    
                // 订阅
                client.subscribe(subTopic);
    
                // 消息发布所需参数
                MqttMessage message = new MqttMessage(content.getBytes());
                message.setQos(qos);
                client.publish(pubTopic, message);
                System.out.println("Message published");
    
                client.disconnect();
                System.out.println("Disconnected");
                client.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();
            }
        } }

Callback message processing class OnMessageCallback.java

package io.emqx;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class OnMessageCallback implements MqttCallback {
    
    
    public void connectionLost(Throwable cause) {
    
    
        // 连接丢失后,一般在这里面进行重连
        System.out.println("连接断开,可以做重连");
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
    
    
        // subscribe后得到的消息会执行到这里面
        System.out.println("接收消息主题:" + topic);
        System.out.println("接收消息Qos:" + message.getQos());
        System.out.println("接收消息内容:" + new String(message.getPayload()));
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
    
    
        System.out.println("deliveryComplete---------" + token.isComplete());
    }
}

Guess you like

Origin blog.csdn.net/weixin_44749255/article/details/131829857