MQTT——服務器搭建(一)

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/5090916.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章