Mosquitto是由Eclipse Foundation开源的MQTT broker,同时也提供了基于C语言的MQTT clients(包括发布端和订阅端)Mosquitto官网
Mosquitto支持Linux、Windows、MacOS、Arm-linux等系统。
# 1、直接clone github中最新代码
git clone https://github.com/eclipse/mosquitto.git
# 2、基于cmake安装
mkdir build && cd build
cmake ..
make
# 2.1、安装编译失败(本人在MacOS Monterey中编译失败),修改下列文件即可。
CMakeLists.txt
option(WITH_BUNDLED_DEPS "Build with bundled dependencies?" ON)
option(WITH_TLS
- "Include SSL/TLS support?" ON)
+ "Include SSL/TLS support?" OFF)
option(WITH_TLS_PSK
- "Include TLS-PSK support (requires WITH_TLS)?" ON)
+ "Include TLS-PSK support (requires WITH_TLS)?" OFF)
option(WITH_EC
- "Include Elliptic Curve support (requires WITH_TLS)?" ON)
+ "Include Elliptic Curve support (requires WITH_TLS)?" OFF)
注释以下两个文件:
plugins/message-timestamp/CMakeLists.txt
plugins/payload-modification/CMakeLists.txt
# 3、编译完成后生成的主要文件说明
CMakeCache.txt
...
src/mosquitto # mosquitto broker
client/mosquitto_pub # mosquitto发布客户端
client/mosquitto_sub # mosquitto订阅客户端
Mosquitto为了方便用户测试,很贴心地提供了一个公网的MQTT broker,网站可直接访问:test.mosquitto.org。测试方法很简单,使用mosquitto_sub订阅一个主题,使用mosquitto_pub向该主题发送一个消息。
# 1、订阅者向test.mosquitto.org订阅主题/test/ttx
./mosquitto_sub -h test.mosquitto.org -t "/test/ttx"
# 2、发布者向test.mosquitto.org发布消息Hello Mosquitto至主题/test/ttx
./mosquitto_pub -h test.mosquitto.org -t "/test/ttx" -m "Hello Mosquitto"
#3、订阅者收到发布者的消息Hello Mosquitto
1、直接到编译出的src目录下运行mosquitto程序,该程序会启动一个mosquitto broker监听localhost的1883端口。
./mosquitto (master✱)
1662991355: mosquitto version 2.0.15 starting
1662991355: Using default config.
1662991355: Starting in local only mode. Connections will only be possible from clients running on this machine.
1662991355: Create a configuration file which defines a listener to allow remote access.
1662991355: For more details see https://mosquitto.org/documentation/authentication-methods/
1662991355: Opening ipv4 listen socket on port 1883.
1662991355: Opening ipv6 listen socket on port 1883.
1662991355: mosquitto version 2.0.15 running
2、跟基于公网的broker测试方法类似,只不过这次的broker是localhost
./mosquitto_sub -h localhost -t "/test/ttx"
./mosquitto_pub -h localhost -t "/test/ttx" -m "Hello Mosquitto"
# broker 监听到的信息
1662991508: New connection from 127.0.0.1:52196 on port 1883.
1662991508: New client connected from 127.0.0.1:52196 as auto-766C9637-15FF-A4CE-92DC-ABBA2FBF3E64 (p2, c1, k60).
1662991545: New connection from 127.0.0.1:52206 on port 1883.
1662991545: New client connected from 127.0.0.1:52206 as auto-C72C458F-B18E-7ED8-67A5-E23633F99CA9 (p2, c1, k60).
1662991545: Client auto-C72C458F-B18E-7ED8-67A5-E23633F99CA9 disconnected.
TODO…