本章将使用Java连接MQTT客户端,实现发布消息,订阅消息,接收消息
引入相关依赖
本例中使用 Maven 来管理依赖的库文件,打开 pom.xml
,加入以下的 JAR 依赖,等待完成相关 JAR 包的下载。
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
完整例子
package paho_demo;
import java.text.MessageFormat;
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 Demo {
public static void main(String[