Mosquitto-1.5在Linux上的安装以及Android客户端的实现
一、关于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 //通过示例配置文件启动
-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.
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 1884 -u root -P 123456 -t topic01 //订阅主题"topic01" mosquitto_pub -h 192.168.153.130 -p 1884 -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(20) //构建出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[]{0, 1, 2}; 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-
posted on 2019-02-27 17:02 sheldon_blogs 阅读(1698) 评论(4) 编辑 收藏 举报