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.