Eclipse Mosquitto是实现MQTT协议版本5.0、3.1.1和3.1的开源消息代理(经EPL / EDL许可)。Mosquitto轻巧,适合在从低功耗单板计算机到完整服务器的所有设备上使用。
MQTT协议提供了一种使用发布/订阅模型执行消息传递的轻量级方法。这使其适用于物联网消息传递,例如具有低功率传感器或移动设备(例如电话,嵌入式计算机或微控制器)的消息传递。
Mosquitto项目还提供了一个用于实现MQTT客户端的C库,以及非常流行的mosquitto_pub和mosquitto_sub命令行MQTT客户端。
一、Mosquitto下载、安装
新的官方Mosquitto下载地址:https://mosquitto.org/download/
旧的Linux官方Mosquitto下载地址:https://mosquitto.org/files/
旧的Windows官方Mosquitto:https://mosquitto.org/files/binary/
以Ubuntu16为例,可以用命令:
#添加到存储库列表
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
#更新软件包
sudo apt-get update
#安装
sudo apt-get install mosquitto
#安装命令行客户端
sudo apt-get install mosquitto-clients
其它Linux可以用命令:
# 下载源代码包
wget https://mosquitto.org/files/source/mosquitto-2.0.8.tar.gz
# 解压
tar zxfv mosquitto-2.0.8.tar.gz
# 进入目录
cd mosquitto-2.0.8
# 编译
make
# 安装
make instal
二、Mosquitto 配置
主要用于用户认证与权限范围。
1、主配置文件:mosquitto.conf
Mosquitto服务器的配置文件路径一般为:/etc/mosquitto/mosquitto.conf,内容一般如下:
pid_file /var/run/mosquitto.pid
# 消息持久存储
persistence true
persistence_location /var/lib/mosquitto/
# 日志文件
log_dest file /var/log/mosquitto/mosquitto.log
# 其他配置
include_dir /etc/mosquitto/conf.d
# 禁止匿名访问
allow_anonymous false
# 认证配置
password_file /etc/mosquitto/pwfile
# 权限配置
acl_file /etc/mosquitto/aclfile
2、认证配置文件:pwfile
如果没有则创建文件,用命令:
touch /etc/mosquitto/pwfile
添加新用户:
服务开启后,输入如下命令,根据提示输入两遍密码:
mosquitto_passwd /etc/mosquitto/pwfile 用户名
3、权限配置文件:aclfile
打开文件
vim /etc/mosquitto/aclfile
编辑内容
# 李雷只能发布以test为前缀的主题,订阅以$SYS开头的主题即系统主题
user lilei
topic write test/#
topic read $SYS/#
# 韩梅梅只能订阅以test为前缀的主题
user hanmeimei
topic read test/#
三、Mosquitto 启动
-c:指定特定配置文件启动
-d:后台运行
mosquitto -c /etc/mosquitto/mosquitto.conf -d
mosquitto以默认的参数启动:
#打开mosquitto服务端
mosquitto -v
四、Mosquitto 发布与订阅
发布使用mosquitto_pub命令,订阅使用mosquitto_sub命令。常用参数介绍:
参数 | 描述 |
---|---|
-h | 服务器主机,默认localhost |
-t | 指定主题 |
-u | 用户名 |
-P | 密码 |
-i | 客户端id,唯一 |
-m | 发布的消息内容 |
订阅:
mosquitto_sub -h localhost -t "test/#" -u hanmeimei -P 123456 -i "client1"
订阅系统主题:
# 订阅客户端存活连接数
mosquitto_sub -h localhost –t '$SYS/broker/clients/active' -u lilei -P 123456 -i "client2"
发布:
mosquitto_pub -h localhost -t "test/abc" -u lilei -P 123456 -i "client3" -m "How are you?"
这时候我们的MQTT服务器就算是搭建好了。