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/5109028.html)会给出具体实现。

posted @ 2015-12-31 13:25  那些年的草木灰  阅读(57074)  评论(8编辑  收藏  举报