使⽤eclipsepaho在java端实现MQTT消息的收发(客户端与服务
端实例)
⼀、MQTT(消息队列)简介
MQTT(MQ Telemetry Transport)是IBM开发的⼀种⽹络应⽤层的协议,提供轻量级的,⽀持可发布/可订阅的的消息推送模式,使设备对设备之间的短消息通信变得简单,⽐如现在应⽤⼴泛的低功耗传感器,⼿机、嵌⼊式计算机、微型控制器等移动设备。
常⽤的有eclipse paho、activeMQ、阿⾥MQTT和其他的实现,本实例使⽤paho
1、使⽤场景:
1、不可靠、⽹络带宽⼩的⽹络
2、运⾏的设备CPU、内存⾮常有限
(我个⼈主要是⽤在服务端与嵌⼊式客户端进⾏消息和⼴告的通信)
2、特点:
1、基于发布/订阅模型的协议
2、他是⼆进制协议,⼆进制的特点就是紧凑、占⽤空间⼩。他的协议头只有2个字节
3、提供了三种消息可能性保障(Qos):0:最多⼀次、1:最少⼀次、2:只有⼀次
3、关键字
1、HOST:搭载MQTT的服务器地址
2、TOPIC:消息主题,可以被客户端订阅,实现对应消息的收发
3、clientId:客户端ID,⽤于服务器对不同客户端的识别
4、subscribe/unsubscribe:客户端对消息主题的订阅和取消订阅
5、Qos:消息的服务质量,当⽹络过载或拥塞时,QoS 能确保重要业务量不受延迟或丢弃
6、Callback:当客户端收到消息后对消息的处理(回调)
7、KeepAliveInterval:客户端与服务器之间的连接是通过发送⼼跳包来保持存活
⼆、JAVA端实例
⾸先导⼊所依赖jar包
1、服务端代码(负责消息的发送)
package com.sc.util.paho;
lipse.paho.client.mqttv3.MqttClient;
lipse.paho.client.mqttv3.MqttConnectOptions;
lipse.paho.client.mqttv3.MqttDeliveryToken;
lipse.paho.client.mqttv3.MqttException;
lipse.paho.client.mqttv3.MqttMessage;
lipse.paho.client.mqttv3.MqttPersistenceException;
lipse.paho.client.mqttv3.MqttTopic;
lipse.paho.client.mqttv3.persist.MemoryPersistence;
/**
* Title:Server 这是发送消息的服务端
* Description: 服务器向多个客户端推送主题,即不同客户端可向服务器订阅相同主题
* @author rao
*/
public class ServerMQTT {
//tcp://MQTT安装的服务器地址:MQTT定义的端⼝号
public static final String HOST = "tcp://192.168.1.102:1883";
//定义⼀个主题
public static final String TOPIC = "pos_message_all";
/
/定义MQTT的ID,可以在MQTT服务配置中指定
private static final String clientid = "server11";
private MqttClient client;
private MqttTopic topic11;
private String userName = "paho";  //⾮必须
private String passWord = "";  //⾮必须
private MqttMessage message;
/**
* 构造函数
* @throws MqttException
*/
public ServerMQTT() throws MqttException {
// MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient(HOST, clientid, new MemoryPersistence());
connect();
}
/**
*  ⽤来连接服务器
*/
private void connect() {
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(userName);
options.CharArray());
// 设置超时时间
options.setConnectionTimeout(10);
// 设置会话⼼跳时间
options.setKeepAliveInterval(20);
try {
client.setCallback(new PushCallback());
topic11 = Topic(TOPIC);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param topic
* @param message
* @throws MqttPersistenceException
* @throws MqttException
*/
public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException,              MqttException {
MqttDeliveryToken token = topic.publish(message);
token.waitForCompletion();
System.out.println("message is published completely! "
+ token.isComplete());
}
/**
*  启动⼊⼝
* @param args
* @throws MqttException
*/
public static void main(String[] args) throws MqttException {
ServerMQTT server = new ServerMQTT();
server.pic11 , ssage);
System.out.ssage.isRetained() + "------ratained状态");
}
}
2、对消息进⾏处理的回调函数代码(必须)
package com.sc.util.paho;
lipse.paho.client.mqttv3.IMqttDeliveryToken;
lipse.paho.client.mqttv3.MqttCallback;
lipse.paho.client.mqttv3.MqttMessage;
/**
* 发布消息的回调类
*
* 必须实现MqttCallback的接⼝并实现对应的相关接⼝⽅法CallBack 类将实现 MqttCallBack。
* 每个客户机标识都需要⼀个回调实例。在此⽰例中,构造函数传递客户机标识以另存为实例数据。 * 在回调中,将它⽤来标识已经启动了该回调的哪个实例。
* 必须在回调类中实现三个⽅法:
*
*  public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。
*
*  public void connectionLost(Throwable cause)在断开连接时调⽤。
*
*  public void deliveryComplete(MqttDeliveryToken token))
*  接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调⽤。
*  由 t 激活此回调。
*
*/
public class PushCallback implements MqttCallback {
public void connectionLost(Throwable cause) {
// 连接丢失后,⼀般在这⾥⾯进⾏重连
System.out.println("连接断开,可以做重连");
}
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("deliveryComplete---------" + token.isComplete());
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
// subscribe后得到的消息会执⾏到这⾥⾯
System.out.println("接收消息主题 : " + topic);
System.out.println("接收消息Qos : " + Qos());
System.out.println("接收消息内容 : " + new Payload()));
}
}
3、客户端代码(接收消息)
package com.sc.util.paho;
import urrent.ScheduledExecutorService;
lipse.paho.client.mqttv3.MqttClient;
lipse.paho.client.mqttv3.MqttConnectOptions;
lipse.paho.client.mqttv3.MqttException;
lipse.paho.client.mqttv3.MqttTopic;
lipse.paho.client.mqttv3.persist.MemoryPersistence;
/**
* 模拟⼀个客户端接收消息
* @author rao
*
*/
public class ClientMQTT {
public static final String HOST = "tcp://192.168.1.102:1883";
public static final String TOPIC1 = "pos_message_all";
private static final String clientid = "client11";
private MqttClient client;
private MqttConnectOptions options;
private String userName = "admin";    //⾮必须
private String passWord = "password";  //⾮必须
@SuppressWarnings("unused")
private ScheduledExecutorService scheduler;
private void start() {
try {
// host为主机名,clientid即连接MQTT的客户端ID,⼀般以唯⼀标识符表⽰,MemoryPersistence设置clientid的保存形式,默认为以内存保存            client = new MqttClient(HOST, clientid, new MemoryPersistence());
// MQTT的连接设置
options = new MqttConnectOptions();
// 设置是否清空session,这⾥如果设置为false表⽰服务器会保留客户端的连接记录,设置为true表⽰每次连接到服务器都以新的⾝份连接
options.setCleanSession(false);
/
/ 设置连接的⽤户名
options.setUserName(userName);
// 设置连接的密码
options.CharArray());
// 设置超时时间单位为秒
options.setConnectionTimeout(10);
// 设置会话⼼跳时间单位为秒服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个⽅法并没有重连的机制
options.setKeepAliveInterval(20);
// 设置回调
client.setCallback(new PushCallback());
MqttTopic topic = Topic(TOPIC1);
//setWill⽅法,如果项⽬中需要知道客户端是否掉线可以调⽤该⽅法。设置最终端⼝的通知消息
//遗嘱        options.setWill(topic, "close".getBytes(), 2, true);
//订阅消息
int[] Qos  = {1};
String[] topic1 = {TOPIC1};
client.subscribe(topic1, Qos);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws MqttException {
ClientMQTT client = new ClientMQTT();
client.start();
}
}
4、运⾏以上代码需要配置服务器
三、将以上代码调整为⼯具类供其他项⽬调⽤
1、服务端代码及调⽤实例
1)服务端代码(需要引⼊之前的回调函数)
package com.scpos.util;
lipse.paho.client.mqttv3.MqttClient;
lipse.paho.client.mqttv3.MqttConnectOptions;
lipse.paho.client.mqttv3.MqttDeliveryToken;
lipse.paho.client.mqttv3.MqttException;
lipse.paho.client.mqttv3.MqttMessage;
lipse.paho.client.mqttv3.MqttPersistenceException;
lipse.paho.client.mqttv3.MqttTopic;
lipse.paho.client.mqttv3.persist.MemoryPersistence;
/**
* Title:Server 这是发送消息的服务端
* Description: 服务器向多个客户端推送主题,即不同客户端可向服务器订阅相同主题
* @author rao
*/
public class ServerMQTTUtil {
//tcp://MQTT安装的服务器地址:MQTT定义的端⼝号
public static final String HOST = "tcp://dev.****:1883";
//定义MQTT的ID,可以在MQTT服务配置中指定
private static final String clientid = "server11";
private MqttClient client;
private MqttTopic mqttTopic;
private String userName = "paho";
private String passWord = "";
/**
* 构造函数
* @throws MqttException
*/
public ServerMQTTUtil(String topic) throws MqttException {
// MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient(HOST, clientid, new MemoryPersistence());
connect(topic);
}
/**
*  ⽤来连接服务器
*/
private void connect(String topic) {
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setUserName(userName);
options.CharArray());
// 设置超时时间
options.setConnectionTimeout(10);
// 设置会话⼼跳时间
options.setKeepAliveInterval(20);
try {
//          client.setCallback(new PushCallback());
mqttTopic = Topic(topic);
} catch (Exception e) {
e.printStackTrace();
}
}
//发送消息并获取回执
public void publish(MqttMessage message) throws MqttPersistenceException,
MqttException, InterruptedException {
MqttDeliveryToken token = mqttTopic.publish(message);
token.waitForCompletion();
activemq默认账号密码
System.out.println("message is published completely! "
+ token.isComplete());
System.out.println("messageId:" + MessageId());
if (client.isConnected())
client.disconnect(10000);
System.out.println("Disconnected: delivery token \"" + token.hashCode()              + "\" received: " + token.isComplete());
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public MqttTopic getMqttTopic() {
return mqttTopic;
}
public void setMqttTopic(MqttTopic mqttTopic) {
this.mqttTopic = mqttTopic;
}
}
2)调⽤处代码
//设置推送消息体
String sendTime = Time();
String msgType = "html";
String title = Title();
String content = Content();
String createTime = CreateTime();
Map<String, Object> data = new HashMap<String, Object>();
data.put("messageId", messageId);
data.put("msgType", msgType);
data.put("title", title);
data.put("content", content);
data.put("createTime", createTime);
data.put("sendTime", sendTime);
msgType = "posMessage";
Map<String, Object> messageMap = new HashMap<String, Object>();            messageMap.put("msgType", msgType);
messageMap.put("data", data);
String MQTTObject = JSONString(messageMap);
System.out.println(MQTTObject);
//将信息写⼊消息体
MqttMessage mqttMessage = new MqttMessage();
mqttMessage.setQos(1);
mqttMessage.setRetained(true);
mqttMessage.Bytes("UTF-8"));
//根据deviceIdList内容进⾏topic设置和发送推送
if (!deviceIdList.equals("all")) {
List deviceList = Arrays.asList(deviceIdList.split(","));
for (int i =0; i < deviceList.size(); i++) {
String topic = "pos_message_" + (i);
ServerMQTTUtil serverMQTTUtil = new ServerMQTTUtil(topic);
serverMQTTUtil.publish(mqttMessage);
System.out.println(mqttMessage.isRetained() + "------ratained状态");                }
} else {
String topic = "pos_message_all";
ServerMQTTUtil serverMQTTUtil = new ServerMQTTUtil(topic);
serverMQTTUtil.publish(mqttMessage);
System.out.println(mqttMessage.isRetained() + "------ratained状态");            }
2、客户端代码及调⽤实例
1)客户端代码

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。