package com.template.util;
import org.eclipse.paho.client.mqttv3.*;
/**
 * @Author：liuxinyue
 * @Package：com.template.util
 * @Project：cloud-server
 * @name：Receive
 * @Date：2024/9/27 19:14
 */
public class Receive {
    public static void main(String[] args) {
        String topic = "vehicle";
        String broker = "tcp://47.101.53.251:1883";
        String clientId = "lxy";

        try (MqttClient sampleClient = new MqttClient(broker, clientId)) {
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: " + broker);
            sampleClient.connect(connOpts);

            System.out.println("Connected");

            sampleClient.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("Connection lost!");
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("Message arrived. Topic: " + topic + " Message: " + new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    // Not used in this example
                }
            });
            sampleClient.subscribe(topic);
            System.out.println("Subscribed to topic \"" + topic + "\"");
        } 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();
        }
    }
}
