1、pom.xm中引入依赖:
<!-- mqtt依赖 开始 -->
<dependency>
<groupId>org.fusesource.mqtt-client</groupId>
<artifactId>mqtt-client</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<!-- mqtt依赖 结束 -->
2、客户端java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
/**
* mqtt 客户端
* @author m
*
*/
public class Client extends HttpServlet{
public static final String HOST = "tcp://api.houuniot.com:18803";//mqtt服务地址
public static final String TOPIC = "qdhg"; //要使用的主题
private static final String clientid = "client001";//客户端标识
private static MqttClient client;
private MqttConnectOptions options;
private String userName = "qdhg";
private String passWord = "DEii2psAhCsHYTqA";
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
try {
// host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient(HOST, clientid, new MemoryPersistence());
// MQTT的连接设置
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(true);
// 设置连接的用户名
options.setUserName(userName);
// 设置连接的密码
options.setPassword(passWord.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
options.setAutomaticReconnect(true);
// 设置回调
client.setCallback(new PushCallback());
// MqttTopic topic = client.getTopic(TOPIC);
//setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
// options.setWill(topic, "close".getBytes(), 2, true);
client.connect(options);
//订阅消息
int[] Qos = {1};
String[] topic1 = {TOPIC};
client.subscribe(topic1, Qos);
} catch (Exception e) {
e.printStackTrace();
}
}
//断线重连
public synchronized void reConnect(){
try {
if(null != client) {
String[] topic2 = {TOPIC};
int[] Qos = {1};
client.subscribe(topic2,Qos);
System.out.println("mqtt===reConnect成功========");
}else {
init();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
3、接收消息
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Component
public class PushCallback implements MqttCallbackExtended {
/**
* 当与服务器的连接丢失时调用此方法。
*/
@Override
public void connectionLost(Throwable cause) {
// TODO Auto-generated method stub
System.out.println("连接断开,可以做重连=" + cause.toString() + "==" + cause.getMessage());
/*
* try { Client c = new Client(); // 连接成功后调用 c.reConnect(); } catch (Exception
* e) { e.printStackTrace(); }
*/
}
/**
* 当来自服务器的消息到达时调用此方法
*/
@Override
public void messageArrived(String topic,MqttMessage message) throws Exception {
// TODO Auto-generated method stub
/*System.out.println("接收MQTT消息主题 : " + topic);
System.out.println("接收MQTT消息Qos : " + message.getQos());
System.out.println("接收MQTT消息内容 : " + new String(message.getPayload(), "UTF-8"));*/
new ThreadMqttMessage(message).start();
}
class ThreadMqttMessage extends Thread {
MqttMessage message=null;
ThreadMqttMessage(MqttMessage message) {
this.message = message;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
JSONObject data = JSONObject.fromObject(new String(message.getPayload(), "UTF-8"));
insertValue((String) data.get("type"), data);
}catch (Exception e) {
// TODO: handle exception
}
}
}
/**
* 当邮件的传递完成时调用,并且已收到确认。对于QoS 0消息,它是 在将消息传递到网络后调用
*
* 交货。对于QoS 1,当接收到puback时调用它,并且
*
* 用于接收pubcomp时的QoS 2。令牌将相同
*
* 消息发布时返回的令牌。
*/
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// TODO Auto-generated method stub
System.out.println("deliveryComplete--------" + token.isComplete());
}
/**
* 成功完成与服务器的连接时调用 reconnect if true,连接是自动重新连接的结果
*/
@Override
public void connectComplete(boolean reconnect, String serverURI) {
// TODO Auto-generated method stub
System.out.println("connectComplete=====reconnect=" + reconnect + ";serverURI=" + serverURI);
try {
Client c = new Client();
// 连接成功后调用
c.reConnect();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* public void connectionLost(Throwable cause) { // 连接丢失后,一般在这里面进行重连
* System.out.println("连接断开,可以做重连"); Client c=new Client();
*
* while(true) { try { // Thread.sleep(1000); System.out.println("重连开始=====");
* c.reConnect(); System.out.println("重连结束====="); break; } catch (Exception e)
* { e.printStackTrace(); continue; } } }
*
* @Override public void deliveryComplete(IMqttDeliveryToken token) {
* System.out.println("deliveryComplete--publish-------" + token.isComplete());
* }
*
* @Override public void messageArrived(String topic, MqttMessage message)
* throws Exception { // subscribe后得到的消息会执行到这里面 System.out.println("接收消息主题 : " +
* topic); System.out.println("接收消息Qos : " + message.getQos());
*
* System.out.println("接收消息内容 : " + new String(message.getPayload())); }
*/
}