1,介绍
mqtt是个网络协议,mosquitto是一个开源的mqtt broker,当然了它也有它的客户端,命令行和API都有,但是一般用它的命令行,而客户端API用paho的,paho是一个开源的mqtt client。很多人把mosquitto叫做服务器,只是为了好理解而已,事实上broker翻译过来是代理者。mqtt的工作原理,就是发布的客户端把话题和消息给broker,broker再转发给订阅的客户端。订阅客户端和发布客户端可以调换身份,而且不限制客户端的数量。
mosquitto 源码链接:https://github.com/eclipse/mosquitto
paho 源码链接 : https://github.com/eclipse/paho.mqtt.c
2,安装代理者和客户端
我这里是debian10.
guoyanzhang@debian:/etc/mosquitto$ sudo apt-get install mosquitto
guoyanzhang@debian:/etc/mosquitto$ sudo apt-get install mosquitto-clients
3, 启动mosquitto
guoyanzhang@debian:/etc/mosquitto$ sudo systemctl start mosquitto
guoyanzhang@debian:/etc/mosquitto$ sudo systemctl status mosquitto
● mosquitto.service - Mosquitto MQTT v3.1/v3.1.1 Broker
Loaded: loaded (/lib/systemd/system/mosquitto.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2020-05-20 21:38:10 HDT; 16s ago
Docs: man:mosquitto.conf(5)
man:mosquitto(8)
Main PID: 28619 (mosquitto)
Tasks: 1 (limit: 4915)
Memory: 1.0M
CGroup: /system.slice/mosquitto.service
└─28619 /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
4,配置mosquitto
guoyanzhang@debian:/etc/mosquitto$ ls
ca_certificates certs conf.d mosquitto.conf
guoyanzhang@debian:/etc/mosquitto$ cat mosquitto.conf
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
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
guoyanzhang@debian:/etc/mosquitto$ cat conf.d/README
Any files placed in this directory that have a .conf ending will be loaded as
config files by the broker. Use this to make your local config.
开始都是在mosquitto.conf里面配置的(现在添加不生效),现在是在conf.d/下的xxx.conf文件里面配置,上面的README就是说,在conf.d目录下的所有的.conf文件都会被broker加载到配置文件中去,如下,我配置了bind_address:
guoyanzhang@debian:/etc/mosquitto$ cat conf.d/default.conf
bind_address 192.168.1.107
5,测试
订阅:
guoyanzhang@debian:/etc/mosquitto$ mosquitto_sub -t "test"
Error: Connection refused
guoyanzhang@debian:/etc/mosquitto$ mosquitto_sub -t "test" -h 192.168.1.107
hi mqtt
发布:
guoyanzhang@debian:~$ mosquitto_pub -t "test" -m "hi mqtt"
Error: Connection refused
guoyanzhang@debian:~$ mosquitto_pub -t "test" -m "hi mqtt" -h 192.168.1.107
guoyanzhang@debian:~$
这里的测试有Error是因为,开始broker绑定的ip是localhost,现在改成了192.168.1.107.