Android MQTT

MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)

基本知识

可参考:

  • 零基础入门学用物联网 – MQTT基础篇 – 目录

MQTT是一个客户端服务端架构的发布/订阅模式的消息传输协议

有三个角色:

  • 服务端
  • 客户端
  • 主题

QoS 服务质量等级

MQTT协议有三种服务质量级别:
QoS = 0 – 最多发一次
QoS = 1 – 最少发一次
QoS = 2 – 保证收一次

QoS=0的情况下,MQTT服务端和客户端不会对消息传输是否成功进行确认和检查。消息能否成功传输全看网络环境是否稳定。

当QoS级别为1时,发送端在消息发送完成后,会检查接收端是否已经成功接收到了消息

MQTT服务质量最高级是2级,即QoS = 2。当MQTT服务质量为2级时,MQTT协议可以确保接收端只接收一次消息

本地搭建MQTT测试

参考:

  • MQTT在Android端的使用详解以及MQTT服务器搭建、Paho客户端使用

1.安装emqx
安装后,cdeqmx目录下,使用如下的命令

# Start emqx
./bin/emqx start# Check Status
./bin/emqx_ctl status# Stop emqx
./bin/emqx stop

启动后打开http://localhost:18083,帐号为admin,密码为public

2.Paho客户端,貌似版本比较老,在Mac上已经无法打开了
这里还是安装emqx提供的的客户端MQTT X

3.在手机上运行教程中提供project,就可以正常测试了

另外免费的在线 MQTT 5 服务器提供了一个免费的MQTT服务器

Broker:broker-cn.emqx.ioTCP 端口:1883Websocket 端口:8083TCP/TLS 端口:8883Websocket/TLS 端口:8084

其它基础教程

  • Android 使用 Kotlin 连接 MQTT

MQTT安全

参考:

  • MQTT安全初探

MQTT支持两种层次的认证:
1.传输层认证,传输层使用TLS认证设备,并且加密了通讯。
2.应用层认证,支持client id / username / password 等方式认证设备,但是只在应用层验证设备,不加密通讯

MQTT TLS/SSL 认证

参考:

  • Android MQTT TLS/SSL 认证
  • Creating an SSL/TLS Android MQTT Client
  • Android Demo使用说明
  • Android MQTT TLS/SSL 认证

一些说明

相关概念

1.公钥、私钥、签名、数字证书

参考:

  • 公钥、私钥、签名、数字证书的关系(图文)
  • 一文彻底搞懂加密、数字签名和数字证书!

2.HTTPS

参考:

  • HTTPS 温故知新(一) —— 开篇

HTTPS单向认证 vs HTTPS双向认证
参考:

  • 扯一扯HTTPS单向认证、双向认证、抓包原理、反抓包策略


相关类

在使用TLS/SSL时,会使用到一些类,如KeyStoreTrustStore

KeyStore

KeyStore,安卓官方文档对其的说明是:

This class represents a storage facility for cryptographic keys and certificates
此类表示加密密钥和证书的存储设施
A KeyStore manages different types of entries. Each type of entry implements the KeyStore.Entry interface. Three basic KeyStore.Entry implementations are provided:
KeyStore管理不同类型的entry,每种类型的entry都实现了KeyStore.Entry接口。提供了三个基本的 KeyStore.Entry 实现

  • KeyStore.PrivateKeyEntry - 这种类型的entry包含一个加密的私钥,可选择以受保护的格式存储以防止未经授权的访问。它还附带相应公钥的证书链
  • KeyStore.SecretKeyEntry - 这种类型的entry包含一个加密的 SecretKey,它可以选择以受保护的格式存储以防止未经授权的访问
  • KeyStore.TrustedCertificateEntry - 这种类型的entry包含一个属于另一方的公钥证书
    密钥库中的每个entry都由“别名”字符串标识

其使用方式,可参考:

  • KeyStore - 官方文档
  • Java KeyStore API

KeyStore 和 TrustStore区别与联系
参考:

  • KeyStore 和 TrustStore区别与联系

比如在客户端(服务请求方)对服务器(服务提供方)发起一次HTTPS请求时,服务器需要向客户端提供认证以便客户端确认这个服务器是否可信。 这里,服务器向客户端提供的认证信息就是自身的证书和公钥,而这些信息,包括对应的私钥,服务器就是通过KeyStore来保存的。 当服务器提供的证书和公钥到了客户端,客户端就要生成一个TrustStore文件保存这些来自服务器证书和公钥。
KeyStore - 一个KeyStore文件可以包含私钥(private key)和关联的证书(certificate)或者一个证书链。证书链由客户端证书和一个或者多个CA证书
TrustStore - 内容 一个TrustStore仅仅用来包含客户端信任的证书,所以,这是一个客户端所信任的来自其他人或者组织的信息的存储文件,而不能用于存储任何安全敏感信息,比如私钥(private key)或者密码。

自签名证书的处理

参考:

  • Accept server’s self-signed ssl certificate in Java client

MQTT相关类介绍

MqttConnectOptions

MqttConnectOptions保存的是客户端如何连接到服务端的一些选项
这些选项与CONNECT报文有密切的关系

主要说明一下
1.setCleanSession(boolean cleanSession)

参考:1-3 连接MQTT服务端
如果cleanSession 被设置为“true”。那么服务端不需要客户端确认收到报文,也不会保存任何报文。在这种情况下,即使客户端错过了服务端发来的报文,也没办法让服务端再次发送报文。其实我们从字面上也很容易理解。cleanSession 的第一个词是clean。这个词的意思是clean(干净)的。服务端一旦发送完报文,就会把报文忘得“干干净净”了。
反过来,如果我们将cleanSession 设置为”false”。那么服务端就知道,后续通讯中,客户端可能会要求我保存没有收到的报文。
从以上的描述不难看出,如果某个客户端用于收发非常重要的信息(比如前文示例中汽车自动驾驶系统),那么该客户端在连接服务端时,应该将cleanSession设置为”false”。这样才能让服务端保存那些没有得到客户端接收确认的信息。以便服务端再次尝试将这些重要信息再次发送给客户端。

相反的,如果某个客户端用于收发不重要的信息(比如前文示例中车载音乐系统)那么该客户端在连接服务端时,应该将cleanSession设置为”true”

请注意,如果需要服务端保存重要报文,光设置cleanSessionfalse是不够的,还需要传递的MQTT信息QoS级别大于0

2.setKeepAliveInterval(int keepAliveInterval)

MQTT服务端运行过程中,当有客户端因为某种原因断开了与服务端的连接,服务端需要实时了解这一情况。KeepAlive (心跳时间间隔)正是用于服务端了解客户端连接情况的。

3.will(遗嘱)相关

参考:2-6 MQTT遗嘱
为了让客户端可以更好的发挥作用,便于服务端管理,MQTT协议允许客户端在“活着”的时候就写好遗嘱,这样一旦客户端意外断线,服务端就可以将客户端的遗嘱公之于众。

客户端的遗嘱只在意外断线时才会发布,如果客户端正常的断开了与服务端的连接,这个遗嘱机制是不会启动的,服务端也不会将客户端的遗嘱公布。

当客户端正常断开连接时,会向服务端发送DISCONNECT报文,服务端接收到该报文后,就知道,客户端是正常断开连接,而并非意外断开连接。

MqttAndroidClient

1.setCallback(MqttCallback callback)

MqttCallback是一个接口,定义如下:

public interface MqttCallback {/*** This method is called when the connection to the server is lost.** @param cause the reason behind the loss of connection.*/void connectionLost(Throwable cause);/*** This method is called when a message arrives from the server.** <p>* This method is invoked synchronously by the MQTT client. An* acknowledgment is not sent back to the server until this* method returns cleanly.</p>* <p>* If an implementation of this method throws an <code>Exception</code>, then the* client will be shut down.  When the client is next re-connected, any QoS* 1 or 2 messages will be redelivered by the server.</p>* <p>* Any additional messages which arrive while an* implementation of this method is running, will build up in memory, and* will then back up on the network.</p>* <p>* If an application needs to persist data, then it* should ensure the data is persisted prior to returning from this method, as* after returning from this method, the message is considered to have been* delivered, and will not be reproducible.</p>* <p>* It is possible to send a new message within an implementation of this callback* (for example, a response to this message), but the implementation must not* disconnect the client, as it will be impossible to send an acknowledgment for* the message being processed, and a deadlock will occur.</p>** @param topic name of the topic on the message was published to* @param message the actual message.* @throws Exception if a terminal error has occurred, and the client should be* shut down.*/void messageArrived(String topic, MqttMessage message) throws Exception;/*** Called when delivery for a message has been completed, and all* acknowledgments have been received. For QoS 0 messages it is* called once the message has been handed to the network for* delivery. For QoS 1 it is called when PUBACK is received and* for QoS 2 when PUBCOMP is received. The token will be the same* token as that returned when the message was published.** @param token the delivery token associated with the message.*/void deliveryComplete(IMqttDeliveryToken token);}

另外MqttCallbackExtended继承自MqttCallback

public interface MqttCallbackExtended extends MqttCallback {/*** Called when the connection to the server is completed successfully.* @param reconnect If true, the connection was the result of automatic reconnect.* @param serverURI The server URI that the connection was made to.*/void connectComplete(boolean reconnect, String serverURI);}

2.connect
通过使用如下的方法来连接

    public IMqttToken connect(MqttConnectOptions options, Object userContext,IMqttActionListener callback) throws MqttException

方法的返回值IMqttToken是一个接口类型

连接结果通过IMqttActionListener回调得到

public interface IMqttActionListener {/*** This method is invoked when an action has completed successfully.  * @param asyncActionToken associated with the action that has completed*/void onSuccess(IMqttToken asyncActionToken);/*** This method is invoked when an action fails.  * If a client is disconnected while an action is in progress * onFailure will be called. For connections* that use cleanSession set to false, any QoS 1 and 2 messages that * are in the process of being delivered will be delivered to the requested* quality of service next time the client connects.  * @param asyncActionToken associated with the action that has failed* @param exception thrown by the action that has failed*/void onFailure(IMqttToken asyncActionToken, Throwable exception);
}

这个地方就与CONNACK 报文有点关系了,参考:

  • 3.2 CONNACK – Acknowledge connection request

Connect Return code如下:

DisconnectedBufferOptions

在一些例子中,有看到,在connect连接成功后,来设置DisconnectedBufferOptions

其定义为:

Holds the set of options that govern the behaviour of Offline (or Disconnected) buffering of messages
保存管理离线(或断开连接)消息缓冲行为的选项集

Android MQTT相关推荐

  1. android mqtt详解_Android mqtt入门 Android studio(转)

    Android mqtt入门 Android studio 2018年04月09日 14:02:30 hbw020 阅读数:1564 分享 mqtt简单使用介绍: 1.as创建工程 2.官网下载mqt ...

  2. 一步步实现Android MQTT详细步骤,附工程文件

    一.lib下载 1,服务的lib org.eclipse.paho.android.service-1.1.1.jar 2,客户端的lib org.eclipse.paho.client.mqttv3 ...

  3. android paho框架,Android Mqtt 客户端paho使用心得

    Android mqtt 客户端实现一般使用以下两个库: implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1 ...

  4. 物联网阿里云——Android Mqtt协议连接阿里云

    实现步骤: 一.云平台端 1.首先在阿里云物联网平台创建产品和设备,获取设备三元组 {       "ProductKey": "a1QRE182gGH",   ...

  5. android mqtt详解_Android 中MQTT协议的使用

    前言 项目中有用到mqtt,碰巧没人负责这一块,所以毛遂自荐就看了一波,下面是一些简单的使用记录,写得不好,仅供参考.若没有mqtt服务器的朋友,建议先建一个mqtt服务,不然看不到效果. 什么是Mq ...

  6. Android MQTT协议

    1.关于MQTT简介 MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是IBM开发的一个即时通讯协议.它是一种发布/订阅,极其简单和轻量级的消息传递 ...

  7. Android MQTT实现消息推送

    飞哥语录:编程说白了就是发送数据,接收数据,处理数据. 1.概述 MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是IBM开发的一个即时通讯协议,有 ...

  8. Android mqtt客户端实例

    build.gredle中配置 dependencies{ api 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0' } 代码实例 pac ...

  9. android mqtt服务器搭建,Mqtt从服务端到Android客户端搭建(mqtt服务端搭建)

    一.简介 MQTT(消息队列遥测传输)是ISO 标准(ISO/IEC PRF 20922)下基于发布/订阅范式的消息协议. 此处不再引入官方文字描述,以个人开发认识浅谈一下 本文分为两部分: 1. M ...

最新文章

  1. (转)详解css3弹性盒模型(Flexbox)
  2. java垃圾回收system_java应用性能调优之详解System的gc垃圾回收方法
  3. zencart 1.5.4 安装问题
  4. unix修改ip和计算机名,UNIX shell获取IP和修改IP
  5. LVS技术浅析-proc参数
  6. 无约束优化算法——牛顿法与拟牛顿法(DFP,BFGS,LBFGS)
  7. 深圳软件开发向前跳转会略过一些节点
  8. codeforces 149E . Martian Strings kmp
  9. 电商垄断的形式不是对某一行业的具体垄断
  10. 解决UnicodeEncodeError: 'gbk' codec can't encode character u'\u25aa' in position 344 : illegal multiby
  11. 基于OpenCV 人工神经网络的喷码字符识别(C++)
  12. bch码原理基于matlab,BCH码编译码matlab仿真
  13. 使用 ffmpeg 进行视频(ts)合并
  14. Ectouch修改虚拟销售数量的方法
  15. 秒杀系统设计的关键点思考
  16. 棉猴论坛VIP之驱动基础系列教程 视频教程
  17. php opc数据,OPC连接获取数据
  18. win7电脑蓝屏怎么办
  19. windows装oracle数据库,在 Windows 上安装 Oracle 数据库 11g
  20. java 麻将胡牌算法_麻将胡牌算法研究

热门文章

  1. 阿里巴巴最新开源“SpringSecurity手册”用户+案例+认证+框架,面面俱到太全了
  2. 开源IT资产管理软件(GIPI)
  3. tornado 报错 NotImplementedError
  4. Python封装模型
  5. 全网素材采集支持采集小程序素材和视频号
  6. 7000字长文详述评价存储系统的技术指标
  7. 线程池面试题一般会怎么问?线程池面试题总结及答案整理
  8. 冷战2017,腾讯金融VS蚂蚁金服过去的一年
  9. node本地测试ajax CMD窗报错:_http_outgoing.js:436 throw new Error('Header %s value must not be undef
  10. 【引语练习题】一般疑问句转化为间接引语