1Java创建项目
2导入依赖
将下面Mqtt的库名复制到 <dependencies> 下面
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
复制后
复制完右上会有如图标志点击加载他会自动下载依赖
下载完成后可以看到库了
3编写订阅者
package org.example;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
//订阅者
public class SubClient {
public static void main(String[] args) throws MqttException {
//创建客户端对象
MqttClient client= new MqttClient("tcp://127.0.0.1:1883","li-Mqtt-1",new MemoryPersistence());
//创建连接配置
MqttConnectOptions options=new MqttConnectOptions();
options.setCleanSession(true);
//将配置设置给客户端
client.connect(options);
//配置回调函数,等待信息
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
System.out.println("连接断开时。。。"+throwable.getMessage());
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
System.out.println("接收信息....主题为:"+s+"---信息为:"+new String(mqttMessage.getPayload()));
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("信息传递完成。。。。"+iMqttDeliveryToken.isComplete());
}
});
//开始订阅
client.subscribe("wd");
System.out.println("订阅已经准备好了");
}
}
4编写发布者
package org.example;
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;
import java.nio.charset.StandardCharsets;
//消息发布者
public class PubClient {
public static void main(String[] args) throws MqttException {
//创建客户端对象
MqttClient client=new MqttClient("tcp://127.0.0.1:1883","li-Mqtt-2",new MemoryPersistence());
//创建连接配置
MqttConnectOptions options=new MqttConnectOptions();
options.setCleanSession(true);
//将配置设置给客户端
client.connect(options);
//创建消息对象
MqttMessage mqttMessage=new MqttMessage("我是消息".getBytes(StandardCharsets.UTF_8));
//设置消息等级
mqttMessage.setQos(2);
//发布消息
client.publish("wd",mqttMessage);
//断开连接
client.disconnect();
//关闭Mqtt客户端
client.close();
}
}