mqtt 是輕量級基於代理的發佈/訂閱的消息傳輸協議,設計思想是開放,簡單,輕量級,且易於實現,這些優勢使得他受用於任何環境java
該協議的特色有:服務器
使用發佈/訂閱消息的模式,提供一對多的消息發佈,解除應用程序耦合網絡
對負載內容屏蔽的消息傳輸session
使用TCP/IO 提供的網絡鏈接eclipse
有三種消息發佈服務質量:tcp
"至多一次",消息發佈徹底依賴底層TCP/IP 網絡,會發生消息丟失或者重複,這一級別可用於以下狀況,環境,傳感器數據,丟失一次度記錄無所謂,由於不久以後會有第二次發送函數
"至少一次" 確保消息到達,但消息重複可能發生設計
「只有一次",確保消息到達一次,這一級別可用於以下狀況,在計費系統中,消息重複或者丟失致使不正確的結果代理
小型傳輸,開銷很小(固定牀都的頭部是2個字節),協議變換最小化,以下降網絡流量code
使用Last will和Testament 特性通知有關客戶端異常中斷的機制
服務器端程序 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())); } } 客戶端程序 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(); } }