一、关于MQTT

  MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议),是一种基于发布/订阅(publish/subscribe)模式的"轻量级"通讯协议,该协议构建于TCP/IP协议上,由IBM在1999年发布。MQTT最大优点在于,可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务。作为一种低开销、低带宽占用的即时通讯协议,使其在物联网、小型设备、移动应用等方面有较广泛的应用。

  MQTT是一个基于客户端-服务器的消息发布/订阅传输协议。MQTT协议是轻量、简单、开放和易于实现的,这些特点使它适用范围非常广泛。在很多情况下,包括受限的环境中,如:机器与机器(M2M)通信和物联网(IoT)。其在,通过卫星链路通信传感器、偶尔拨号的医疗设备、智能家居、及一些小型化设备中已广泛使用。

  而Mosquitto是一个实现了MQTT3.1协议的代理服务器,由MQTT协议创始人之一的Andy Stanford-Clark开发,它为我们提供了非常棒的轻量级数据交换的解决方案,本文将基于mosquitto实现Android手机和阿里云服务器的mqtt通讯。

二、Mosquitto在Ubuntu上安装

1)下载源码压缩包 :https://mosquitto.org/download/

2)解压源代码包:

tar -zxvf mosquitto-1.5.tar.gz

3)安装编译环境:

sudo apt-get install gcc

sudo apt-get install libssl-dev

sudo apt-get install g++

sudo apt-get install uuid-dev

sudo apt-get install libc-ares-dev

sudo apt-get install libc-ares2

4)进入第2步中解压开的源代码目录,对源代码进行编译:

cd mosquito-1.5

sudo make    // 编译生成可执行文件

sudo make install    // 安装到系统目录,可省略

 注:其中config.mk包括了多个选项, 可按需关闭或开启,但一旦开启则需要先安装对应的模块:

    # 是否支持tcpd/libwrap功能.
#WITH_WRAP:=yes # 是否开启SSL/TLS支持
#WITH_TLS:=yes # 是否开启TLS/PSK支持
#WITH_TLS_PSK:=yes # Comment out to disable client client threading support.
#WITH_THREADING:=yes # 是否使用严格的协议版本(老版本兼容会有点问题)
#WITH_STRICT_PROTOCOL:=yes # 是否开启桥接模式
#WITH_BRIDGE:=yes # 是否开启持久化功能
#WITH_PERSISTENCE:=yes # 是否监控运行状态
#WITH_MEMORY_TRACKING:=yes

5)启动服务

cd src

mosquito -c mosquitto.conf.example      //通过示例配置文件启动

  通过 mosquito --help 查看详细选项说明:

 -c : specify the broker config file.
-d : put the broker into the background after starting.
-h : display this help.
-p : start the broker listening on the specified port.
Not recommended in conjunction with the -c option.
-v : verbose mode - enable all logging types. This overrides
any logging options given in the config file.

 另外 主题订阅 和 消息发布 的客户端文件生成在 client 目录,同样通过如下指令查看详细参数说明:

 mosquitto_sub --help

mosquitto_sub is a simple mqtt client that will subscribe to a set of topics and print all messages it receives.
mosquitto_sub version 1.5 running on libmosquitto 1.5.0. Usage: mosquitto_sub {[-h host] [-p port] [-u username [-P password]] -t topic | -L URL [-t topic]}
                     [-c] [-k keepalive] [-q qos]
                     [-C msg_count] [-R] [--retained-only] [-T filter_out] [-U topic ...]
                     [-F format]
                     [-W timeout_secs]
                     [-A bind_address]
                     [-i id] [-I id_prefix]
                     [-d] [-N] [--quiet] [-v]
                     [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                     [--proxy socks-url]
       mosquitto_sub --help  -A : bind the outgoing socket to this host/ip address. Use to control which interface
      the client communicates over.
 -c : disable 'clean session' (store subscription and pending messages when client disconnects).
 -C : disconnect and exit after receiving the 'msg_count' messages.
 -d : enable debug messages.
 -F : output format.
 -h : mqtt host to connect to. Defaults to localhost.
 -i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.
 -I : define the client id as id_prefix appended with the process id. Useful for when the
      broker is using the clientid_prefixes option.
 -k : keep alive in seconds for this client. Defaults to 60.
 -L : specify user, password, hostname, port and topic as a URL in the form:
      mqtt(s)://[username[:password]@]host[:port]/topic
 -N : do not add an end of line character when printing the payload.
 -p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.
 -P : provide a password
 -q : quality of service level to use for the subscription. Defaults to 0.
 -R : do not print stale messages (those with retain set).
 -t : mqtt topic to subscribe to. May be repeated multiple times.
 -T : topic string to filter out of results. May be repeated.
 -u : provide a username
 -U : unsubscribe from a topic. May be repeated.
 -v : print published messages verbosely.
 -V : specify the version of the MQTT protocol to use when connecting.
      Can be mqttv31 or mqttv311. Defaults to mqttv311.
 -W : Specifies a timeout in seconds how long to process incoming MQTT messages.
 --help : display this message.
 --quiet : don't print error messages.
 --retained-only : only handle messages with the retained flag set, and exit when the
                   first non-retained message is received.
 --will-payload : payload for the client Will, which is sent by the broker in case of
                  unexpected disconnection. If not given and will-topic is set, a zero
                  length message will be sent.
 --will-qos : QoS level for the client Will.
 --will-retain : if given, make the client Will retained.
 --will-topic : the topic on which to publish the client Will.
 --proxy : SOCKS5 proxy URL of the form:
           socks5h://[username[:password]@]hostname[:port]
           Only "none" and "username" authentication is supported. See http://mosquitto.org/ for more information.

 mosquitto_pub --help

mosquitto_pub is a simple mqtt client that will publish a message on a single topic and exit.
mosquitto_pub version 1.5 running on libmosquitto 1.5.0. Usage: mosquitto_pub {[-h host] [-p port] [-u username [-P password]] -t topic | -L URL}
                     {-f file | -l | -n | -m message}
                     [-c] [-k keepalive] [-q qos] [-r]
                     [-A bind_address]
                     [-i id] [-I id_prefix]
                     [-d] [--quiet]
                     [-M max_inflight]
                     [-u username [-P password]]
                     [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]
                     [--proxy socks-url]
       mosquitto_pub --help  -A : bind the outgoing socket to this host/ip address. Use to control which interface
      the client communicates over.
 -d : enable debug messages.
 -f : send the contents of a file as the message.
 -h : mqtt host to connect to. Defaults to localhost.
 -i : id to use for this client. Defaults to mosquitto_pub_ appended with the process id.
 -I : define the client id as id_prefix appended with the process id. Useful for when the
      broker is using the clientid_prefixes option.
 -k : keep alive in seconds for this client. Defaults to 60.
 -L : specify user, password, hostname, port and topic as a URL in the form:
      mqtt(s)://[username[:password]@]host[:port]/topic
 -l : read messages from stdin, sending a separate message for each line.
 -m : message payload to send.
 -M : the maximum inflight messages for QoS 1/2..
 -n : send a null (zero length) message.
 -p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.
 -P : provide a password
 -q : quality of service level to use for all messages. Defaults to 0.
 -r : message should be retained.
 -s : read message from stdin, sending the entire input as a message.
 -t : mqtt topic to publish to.
 -u : provide a username
 -V : specify the version of the MQTT protocol to use when connecting.
      Can be mqttv31 or mqttv311. Defaults to mqttv311.
 --help : display this message.
 --quiet : don't print error messages.
 --will-payload : payload for the client Will, which is sent by the broker in case of
                  unexpected disconnection. If not given and will-topic is set, a zero
                  length message will be sent.
 --will-qos : QoS level for the client Will.
 --will-retain : if given, make the client Will retained.
 --will-topic : the topic on which to publish the client Will.
 --proxy : SOCKS5 proxy URL of the form:
           socks5h://[username[:password]@]hostname[:port]
           Only "none" and "username" authentication is supported. See http://mosquitto.org/ for more information.

使用示例(通过三个终端分别输入以下指令):

mosquitto -c mosquitto.conf -p 1884  //启动服务,如果不指定端口则默认使用1883
mosquitto_sub -h 192.168.153.130 -p -u root -P -t topic01 //订阅主题"topic01"
mosquitto_pub -h 192.168.153.130 -p -t topic01 -m "message01"   //发布消息给订阅"topic01"的订阅客户端

 通过以上步骤大致了解mosquitto在Linux系统上的安装和使用方法,同样在阿里云服务器上运行mosquitto后,即可通过手机MQTT客户端与云服务器端进行消息交互。

 PS:阿里云服务器1883端口默认被屏蔽,需要自己另外配置一个端口!

、Mqtt Android客户端开发

 基于Android的Mqtt客户端组件进行接口封装,使用更加简易:

(1)构建MqttService对象

  /**
* 构建EasyMqttService对象
*/
private void buildEasyMqttService() {
mqttService = new EasyMqttService.Builder()
//设置自动重连
.autoReconnect(true)
//设置不清除回话session 可收到服务器之前发出的推送消息
.cleanSession(false)
//唯一标示 保证每个设备都唯一就可以 建议 imei
.clientId("your clientId")
//mqtt服务器地址 格式例如:tcp://10.0.261.159:1883
.serverUrl("your mqtt servier url")
//心跳包默认的发送间隔
.keepAliveInterval()
//构建出EasyMqttService 建议用application的context
.bulid(this.getApplicationContext());
}

(2)连接Mqtt服务器

  /**
* 连接Mqtt服务器
*/
private void connect() {
mqttService.connect(new IEasyMqttCallBack() {
@Override
public void messageArrived(String topic, String message, int qos) {
//推送消息到达
} @Override
public void connectionLost(Throwable arg0) {
//连接断开
} @Override
public void deliveryComplete(IMqttDeliveryToken arg0) { } @Override
public void connectSuccess(IMqttToken arg0) {
//连接成功
} @Override
public void connectFailed(IMqttToken arg0, Throwable arg1) {
//连接失败
}
});
}

(3)订阅主题

   /**
* 订阅主题 这里订阅三个主题分别是"a", "b", "c"
*/
private void subscribe() {
String[] topics = new String[]{"a", "b", "c"};
//主题对应的推送策略 分别是0, 1, 2 建议服务端和客户端配置的主题一致
// 0 表示只会发送一次推送消息 收到不收到都不关心
// 1 保证能收到消息,但不一定只收到一条
// 2 保证收到切只能收到一条消息
int[] qoss = new int[]{, , };
mqttService.subscribe(topics, qoss);
}

(4)关闭连接

     /**
* 关闭连接
*/
private void close() {
mqttService.close();
}

(5)断开连接

   /**
* 断开连接
*/
private void disconnect() {
mqttService.disconnect();
}

(6)判断连接状态

    /**
* 判断服务是否连接
*/
private boolean isConnected() {
return mqttService.isConnected();
}

(7)发布消息

/**
* 发布消息
*/
public void publish(String msg, String topic, int qos, boolean retained) {
try {
client.publish(topic, msg.getBytes(), qos, retained);
} catch (Exception e) {
e.printStackTrace();
}
}

完整的Demo实现了UI动态输入及消息显示,可用于对mqtt服务器进行测试,已上传至GitHub:https://github.com/dragonforgithub/SmartControl

编译生成的Linux及Android客户端软件已传至百度云:链接:https://pan.baidu.com/s/1M_fCCITsW2cXGQLo3MWW0Q  提取码:9r6p

另外可以参考eclipse出品的Android Demo进一步学习: https://github.com/eclipse/paho.mqtt.android

-end-

Mosquitto-1.5在Linux上的安装以及Android客户端的实现的更多相关文章

  1. jemalloc在linux上从安装到使用

    jemalloc在linux上从安装到使用 上次在引导大家安装Redis时提到可能会报错:  发现了redis有用到jemalloc. 首先,jemalloc是干什么的? 我们看看作者自己的介绍: j ...

  2. 分布式缓存技术redis学习系列(一)——redis简介以及linux上的安装

    redis简介 redis是NoSQL(No Only SQL,非关系型数据库)的一种,NoSQL是以Key-Value的形式存储数据.当前主流的分布式缓存技术有redis,memcached,ssd ...

  3. GIT在Linux上的安装和使用简介

    GIT最初是由Linus Benedict Torvalds为了更有效地管理Linux内核开发而创立的分布式版本控制软件,与常用的版本控制工具如CVS.Subversion不同,它不必服务器端软件支持 ...

  4. 分布式缓存技术redis学习(一)——redis简介以及linux上的安装

    redis简介 redis是NoSQL(No Only SQL,非关系型数据库)的一种,NoSQL是以Key-Value的形式存储数据.当前主流的分布式缓存技术有redis,memcached,ssd ...

  5. 在Linux上怎么安装和配置Apache Samza

    samza是一个分布式的流式数据处理框架(streaming processing),它是基于Kafka消息队列来实现类实时的流式数据处理的.(准确的说,samza是通过模块化的形式来使用kafka的 ...

  6. ODI11G 在Linux上的安装配置

    ODI11G 在Linux上的安装配置 OS环境:Red hat Linux x86_64 一.JDK安装 1. 去oracle官网上下载 http://www.oracle.com/technetw ...

  7. 【JAVAWEB学习笔记】27_Redis:在Linux上的安装、Jedis和常用命令

    一.Redis简介 1.关于关系型数据库和nosql数据库 关系型数据库是基于关系表的数据库,最终会将数据持久化到磁盘上,而nosql数据     库是基于特殊的结构,并将数据存储到内存的数据库.从性 ...

  8. 【数据库】Mean web开发 04-MongoDB在Linux上的安装及遇到的问题

    简介 Mean是JavaScript的全栈开发框架.更多介绍 用MongoDB实现持久数据的存储是Mean Web全栈开发中的一部分. MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非 ...

  9. linux上redis安装配置及其防漏洞配置及其攻击方法

    Linux上redis安装: 需先在服务器上安装yum(虚拟机可使用挂载的方式安装) 安装配置所需要的环境运行指令:  yum -y install gcc 进入解压文件执行make 指令进行编译 执 ...

随机推荐

  1. 设置div 高度 总结

    如果将div 的height 设置为固定的像素值,在不同分辨率的显示屏上,会看到div 在浏览器上的高度不一致.可以以百分比的形式设置div 的高度.注意,这个百分比是针对div 的上一层标签而言的, ...

  2. Delphi中有关窗口绘制

    Invalidate方法通知Windows应该重新绘制表单的整个表面.最重要的是Invalidate不会立即强制执行绘制操作. Windows只是存储请求,并且只会响应它当前程序完全执行后,并且只要系 ...

  3. VKD224B触摸芯片调试笔记

    1.通过阅读datasheet了解芯片怎么使用,一般datasheet会提供参考电路.和相应的电气参数. 通过上面的表格可以知道芯片的供电,所需电流. 这个芯片可以通过引脚选择模式.通过上面的选项设置 ...

  4. DB2数据库许可证过期 SQLSTATE=42968

    Linux查看DB2许可信息: 执行su - db2inst1命令,进入db2命令行,执行db2licm -l命令. Windows查看DB2许可信息: windows+R打开黑窗口,db2cmd进入 ...

  5. docker overlay

    http://blog.csdn.net/jiangshouzhuang/article/details/52822125

  6. Python自然语言处理笔记【二】文本分类之监督式分类的细节问题

    一.选择正确的特征 1.建立分类器的工作中如何选择相关特征,并且为其编码来表示这些特征是首要问题. 2.特征提取,要避免过拟合或者欠拟合 过拟合,是提供的特征太多,使得算法高度依赖训练数据的特性,而对 ...

  7. dp小总结

    写在前面 Just some easy problem solving with dynamic programming. (Given me a dynamic programming table, ...

  8. FutureBuilder的使用以及防止FutureBuilder不必要重绘的两种方法

    https://blog.csdn.net/u011272795/article/details/83010974 https://segmentfault.com/a/119000001421934 ...

  9. Linux学习笔记之时间同步the NTP socket is in use, exiting问题

    [root@app1 ~]# ntpdate ntp.api.bz 17 Apr 14:39:09 ntpdate[24744]: the NTP socket is in use, exiting ...

  10. linux centos7添加ip黑名单禁止某个ip访问

    centos7用的是firewall 添加单个黑名单只需要把ip添加到 /etc/hosts.deny 格式  sshd:$IP:deny vim /etc/hosts.deny   添加你要禁止的i ...