Java MQTT訂閱端,可訂閱萬用字元(/#)

黑鬍子大叔的小屋發表於2020-11-19

Java實現MQTT訂閱端,可訂閱萬用字元(/#)

在做MQTT訂閱端時報錯:

The topic name MUST NOT contain any wildcard characters (#+)

提示Topic中不能包含萬用字元

  • 主函式

PublishSubscribe.java

package Test;

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

import java.util.Map;
import java.util.UUID;


 
/**
 * mqtt的釋出和訂閱
 *
 * @author wzq
 */
public class PublishSubscribe {
 
 
    private static String serviceURI = "tcp://192.168.32.160:1883";
    private static String clientID = UUID.randomUUID().toString();
    private static MqttClientPersistence persistence = new MemoryPersistence();
    //如果mqtt服務配置了匿名訪問,則不需要使用使用者名稱和密碼就可以實現訊息的訂閱和釋出
    private static String username = "admin";
    private static String password = "123456";
    private static String topic = "capability/#";
    /*
        訊息服務質量,一共有三個:
        0:盡力而為。訊息可能會丟,但絕不會重複傳輸
        1:訊息絕不會丟,但可能會重複傳輸
        2:恰好一次。每條訊息肯定會被傳輸一次且僅傳輸一次
     */
    private static int qos = 0;
 
    /**
     * 訊息釋出
     *
     * @author wzq
     **/
    public static void publish() {
        try {
            MqttClient client = new MqttClient(serviceURI, clientID, persistence);
            MqttConnectOptions connectOptions = new MqttConnectOptions();
//            connectOptions.setUserName(username);
//            connectOptions.setPassword(password.toCharArray());
            connectOptions.setCleanSession(false);
            //釋出者連線服務
            client.connect(connectOptions);
            System.out.println("釋出者連線狀態: " + client.isConnected());
            MqttTopic mqttTopic = client.getTopic(topic);
            //MqttMessage mqttMessage = new MqttMessage(message.getBytes());
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setQos(qos);
            int i = 1;
            String message = "hello,world-";
            while (true) {
                String payLoad = message + i++;
                mqttMessage.setPayload(payLoad.getBytes());
                MqttDeliveryToken deliveryToken = mqttTopic.publish(mqttMessage);
                if (!deliveryToken.isComplete()) {
                    System.out.println("釋出者釋出訊息: " + payLoad + " 失敗");
                    deliveryToken.waitForCompletion();
                } else {
                    System.out.println("釋出者釋出訊息: " + payLoad + " 成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 訊息訂閱
     *
     * @author wzq
     **/
    static Map<String, Object> map1;
    public static Map<String, Object> subscribe() {
    	
        try {
            MqttClient client = new MqttClient(serviceURI, clientID, persistence);
            client.setCallback(new PushCallback());
            MqttConnectOptions connectOptions = new MqttConnectOptions();
            connectOptions.setUserName(username);
            connectOptions.setPassword(password.toCharArray());
            connectOptions.setCleanSession(false);
            //訂閱者連線訂閱主題
            client.connect(connectOptions);
            client.subscribe(topic, qos);
            System.out.println("訂閱者連線狀態: " + client.isConnected());

        } catch (MqttException e) {
            e.printStackTrace();
        }
        return map1;
    }
 
    public static void anay(String topic,String message){

    	System.out.println("topic:"+topic);
    	System.out.println("message:"+message);
    	String topic_content=topic;
    	String message_content=message;

    }
}
  • 回撥函式

PushCallback.java

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

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class PushCallback implements MqttCallback {

	static int num=0;

	@Override
	public void connectionLost(Throwable arg0) {
		// TODO Auto-generated method stub
        System.out.println("訂閱者連線丟失...");
        System.out.println(arg0.getMessage());
	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
		// TODO Auto-generated method stub
    	System.out.println("訂閱者接收到主題: " + arg0.toString());
        System.out.println("訂閱者接收到訊息: " + arg1.toString());
        anay(arg0.toString(), arg1.toString());
        
	}
    public static void anay(String topic,String message){
    	num++;
    	if(num>1){
    		JsonParser parser = new JsonParser() ;
    		JsonObject object=(JsonObject) parser.parse(message);
    		object.addProperty("topic", topic);
    		Client.array.add(object);
    		System.out.println(Client.array);
    	}
    }

}

  • 測試

client.java

package Test;

import java.util.Map;

import com.google.gson.JsonArray;

public class Client {

	static JsonArray array = new JsonArray();
	public static void main(String[] args) {
		PublishSubscribe ps=new PublishSubscribe();
		Map<String, Object> map=ps.subscribe();
	}
}

相關文章