MQTT介紹
MQTT,是IBM推出的一種針對移動終端設備的基於TCP/IP的發布/預訂協議,可以連接大量的遠程傳感器和控制設備:
- 輕量級的消息訂閱和發布(publish/subscribe)協議
- 建立在TCP/IP協議之上
IoT,internet of things,物聯網,MQTT在這方面應用較多。
MQTT協議是針對如下情況設計的:
- M2M(Machine to Machine) communication,機器端到端通信,比如傳感器之間的數據通訊
- 因為是Machine to Machine,需要考慮:
- Machine,或者叫設備,比如溫度傳感器,硬件能力很弱,協議要考慮盡量小的資源消耗,比如計算能力和存儲等
- M2M可能是無線連接,網絡不穩定,帶寬也比較小
MQTT協議的架構,用一個示例說明。比如有1個溫度傳感器(1個Machine),2個小的顯示屏(2個Machine),顯示屏要顯示溫度傳感器的溫度值。
顯示器需要先通過MQTT協議subscribe(訂閱)一個比如叫temperature的topic(主題):
當溫度傳感器publish(發布)溫度數據,顯示器就可以收到了:
注:以上兩張圖,取自MQTT and CoAP, IoT Protocols
協議里還有2個主要的角色:
- client,客戶端
- broker,服務器端
它們是通過TCP/IP協議連接的。因為MQTT是協議,所以不能拿來直接用的,就好比HTTP協議一樣。需要找實現這個協議的庫或者服務器來運行。
MQTT的官網見:http://mqtt.org/。其中http://mqtt.org/software里面提供了官方推薦的各種服務器和客戶端使用的各種語言版本的API。
下面以服務器apache-apollo-1.7.1為例,在windows環境下測試。
1、在這里下載Apollo服務器,下載后解壓。如下圖所示:
bin下包含apollo和apollo.cmd兩個文件:
2、運行apache-apollo-1.7.1\bin\apollo.cmd,輸入create mybroker(名字任意取,這里是根據官網介紹的來取的)創建服務器實例,服務器實例包含了所有的配置,運行時數據等,並且和一個服務器進程關聯。如果雙擊apollo.cmd出現閃一下就關閉的情況,則需要在命令行中敲入命令:
create mybroker之后會在bin目錄下生成mybroker文件夾。
里面包含有很多信息,其中etc\apollo.xml文件下是配置服務器信息的文件,etc\users.properties文件包含連接MQTT服務器時用到的用戶名和密碼,后面會介紹,可以修改原始的admin=password,可以接着換行添加新的用戶名密碼。
3、打開cmd,運行apache-apollo-1.7.1\bin\mybroker\bin\apollo-broker.cmd run 開啟服務器,如下圖:
可以在瀏覽器中輸入http://127.0.0.1:61680/,其自動轉入:http://127.0.0.1:61680/console/index.html,apollo的登錄頁面。
此界面表示已經安裝成功:該登錄的用戶名和密碼在\apache-apollo-1.7.1\bin\mybroker\etc\users.properties里,打開users.properties文件:
## ---------------------------------------------------------------------------
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements. See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License. You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ---------------------------------------------------------------------------
#
# The list of users that can login. This file supports both plain text or
# encrypted passwords. Here is an example what an encrypted password
# would look like:
#
# admin=ENC(Cf3Jf3tM+UrSOoaKU50od5CuBa8rxjoL)
#
admin=password
經過上面的簡單步驟,服務器基本上就已經完成。輸入admin,password就可以登錄了,如下圖:
用來通信的具體代碼,在下文中(http://www.cnblogs.com/chenrunlin/p/5109028.html)會給出具體實現。