MQTT协议发布(pub)/订阅(sub)数据

pom.xml
<dependencies>
	<dependency>
		<groupId>org.eclipse.pahogroupId>
		<artifactId>org.eclipse.paho.client.mqttv3artifactId>
		<version>1.2.2version>
	dependency>
dependencies>
PublishTest.java
package com.mqtt;

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 PublishTest {

    public static void main(String[] args) {
        String subTopic = "data/clientid/+";
        String pubTopic = "data/clientid/88888";
        String content = "hello mqtt !";
        int qos = 2;
        String broker = "tcp://127.0.0.1:1883";
        String clientId = "clientid";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName("clientid");
            connOpts.setPassword("password".toCharArray());
            // 保留会话
            connOpts.setCleanSession(false);
            // 设置回调
            //client.setCallback(new OnMessageCallback());
            // 建立连接
            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);
            message.setRetained(true);
            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();
        }
    }
}
OnMessageCallback.java
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("连接断开,可以做重连");
        new SubscribeTest().start();
    }

    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());
    }
}
SubscribeTest.java

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class SubscribeTest {
    public void start() {
        String subTopic = "iot/KYuesJkBSNy38WGdhpLcvA/+";
        int qos = 2;
        String broker = "tcp://127.0.0.1:1883";
        String clientId = "clientid";
        MemoryPersistence persistence = new MemoryPersistence();
        try {
                final MqttClient client = new MqttClient(broker, clientId, persistence);
                // MQTT 连接选项
                MqttConnectOptions connOpts = new MqttConnectOptions();
                connOpts.setUserName("clientid");
                connOpts.setPassword("password".toCharArray());
                // 保留会话
                connOpts.setCleanSession(false);
                // 设置回调
                client.setCallback(new MqttCallback() {
                    public void connectionLost(Throwable throwable) {
                        System.out.println("连接断开,可以做重连");
                        try {
                            if(!client.isConnected()){
                                client.reconnect();
                            }
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }
                    }

                    public void messageArrived(String topic, MqttMessage message) throws Exception {
                        System.out.println("接收消息主题:" + topic);
                        System.out.println("接收消息Qos:" + message.getQos());
                        System.out.println("接收消息内容:" + new String(message.getPayload()));
                        System.out.println("=====================================");
                    }

                    public void deliveryComplete(IMqttDeliveryToken token) {
                        System.out.println("deliveryComplete---------" + token.isComplete());
                    }
                });
                // 建立连接
                System.out.println("Connecting to broker: " + broker);
                client.connect(connOpts);
                System.out.println("Connected");
                //System.out.println("Publishing message: " + content);

                // 订阅
                client.subscribe(subTopic);
                //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();
        }

    }

    public static void main(String[] args) {
        SubscribeTest s = new SubscribeTest();
        s.start();
    }
}

https://mqtt.org/
https://www.emqx.io/cn/mqtt

你可能感兴趣的:(Java,java,MQTT)