mqtt 是輕量級基於代理的發布/訂閱的消息傳輸協議,設計思想是開放,簡單,輕量級,且易於實現,這些優點使得他受用於任何環境
該協議的特點有:
使用發布/訂閱消息的模式,提供一對多的消息發布,解除應用程序耦合
對負載內容屏蔽的消息傳輸
使用TCP/IO 提供的網絡連接
有三種消息發布服務質量:
"至多一次",消息發布完全依賴底層TCP/IP 網絡,會發生消息丟失或者重復,這一級別可用於如下情況,環境,傳感器數據,丟失一次度記錄無所謂,因為不久之后會有第二次發送
"至少一次" 確保消息到達,但消息重復可能發生
“只有一次",確保消息到達一次,這一級別可用於如下情況,在計費系統中,消息重復或者丟失導致不正確的結果
小型傳輸,開銷很小(固定床都的頭部是2個字節),協議變換最小化,以降低網絡流量
使用Last will和Testament 特性通知有關客戶端異常中斷的機制
1:配置環境
2:服務器端程序
package com.example; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttPersistenceException; import org.eclipse.paho.client.mqttv3.MqttTopic; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; /** * Description * 服務器向多個客戶端推送主題,即不同客戶端可向服務器訂閱相同主題 * Company Beijing * author youxuan E-mail:xuanyouwu@163.com * date createTime:16/7/13 * version */ public class Server { public static final String HOST = "tcp://101.200.133.189:1883"; public static final String TOPIC = "toclient/124"; public static final String TOPIC125 = "toclient/125"; private static final String clientid = "server"; private MqttClient client; private MqttTopic topic; private MqttTopic topic125; private String userName = "admin"; private String passWord = "password"; private MqttMessage message; public Server() 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.setPassword(passWord.toCharArray()); // 設置超時時間 options.setConnectionTimeout(10); // 設置會話心跳時間 options.setKeepAliveInterval(20); try { client.setCallback(new PushCallback()); client.connect(options); topic = client.getTopic(TOPIC); topic125 = client.getTopic(TOPIC125); } catch (Exception e) { e.printStackTrace(); } } 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()); } public static void main(String[] args) throws MqttException { Server server = new Server(); server.message = new MqttMessage(); server.message.setQos(2); server.message.setRetained(true); server.message.setPayload("給客戶端124推送的信息:wuyouxuan".getBytes()); server.publish(server.topic, server.message); server.message = new MqttMessage(); server.message.setQos(2); server.message.setRetained(true); server.message.setPayload("給客戶端125推送的信息:wuyouxuan".getBytes()); server.publish(server.topic125, server.message); System.out.println(server.message.isRetained() + "------ratained狀態"); } }
回調監聽
package com.example; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.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 消息的傳遞令牌時調用。 * 由 MqttClient.connect 激活此回調。 * */ 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 : " + message.getQos()); System.out.println("接收消息內容 : " + new String(message.getPayload())); } }
3:客戶端程序
package com.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.MqttTopic; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import java.util.concurrent.ScheduledExecutorService; /** * Description * 客戶端程序 * Company Beijing * author youxuan E-mail:xuanyouwu@163.com * date createTime:16/7/13 * version */ public class Client { public static final String HOST = "tcp://101.200.133.189:1883"; public static final String TOPIC = "toclient/124"; private static final String clientid = "client124"; private MqttClient client; private MqttConnectOptions options; private String userName = "admin"; private String passWord = "password"; 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(true); // 設置連接的用戶名 options.setUserName(userName); // 設置連接的密碼 options.setPassword(passWord.toCharArray()); // 設置超時時間 單位為秒 options.setConnectionTimeout(10); // 設置會話心跳時間 單位為秒 服務器會每隔1.5*20秒的時間向客戶端發送個消息判斷客戶端是否在線,但這個方法並沒有重連的機制 options.setKeepAliveInterval(20); // 設置回調 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 static void main(String[] args) throws MqttException { Client client = new Client(); client.start(); } }
參考網站:
https://segmentfault.com/a/1190000002809450#articleHeader0
github 開源項目 https://github.com/fusesource/mqtt-client
運行效果: