Linux版本可参考此大佬文章
Linux下MQTT环境的简单应用及搭建——之Mosquitto-CSDN博客
Mosquitto下载网址
- 自行选择需要的包Download | Eclipse Mosquitto
- 根据我的版本下载https://mosquitto.org/files/binary/win64/mosquitto-2.0.18-install-windows-x64.exe
下载安装完成后
- 进入mosquitto的安装目录,找到mosquitto.conf配置文件
修改mosquitto指定的监听端口 listener 7788
默认配置文件可能注释了,取消设置即可
2.我这边开启mosquitto的匿名登录功能,如果需要授权不用取消此注释
allow_anonymous true
3.修改配置用户的密码文件路径(这里要用绝对路径)
password_file D:\other\mosquitto\pwfile.example
最后一步
启动Mosquitto Broker服务
或者使用命令行启动
mosquitto.exe -c mosquitto.conf -v
-c:指定配置文件
-v:查看输出日志信息
tip:windows查看指定端口是否启动:
netstat -ano | findstr <端口号>
测试
可python也可使用命令行测试
命令行测试
进入安装目录里启动broker
mosquitto.exe -c mosquitto.conf -v
进入安装目录里新打开一个终端,启动sub
mosquitto_sub -t "test1"
-t:订阅topic
进入安装目录里新打开一个终端,启动sub
mosquitto_pub -t "test1" -m "hello mqttfx"
-m:发送消息
python测试
安装paho模块
pip install paho-mqtt
写一个订阅者的代码文件名为sub.py
注意这里的ip、端口号、主题名(topic)要设置为自己配置的
import paho.mqtt.client as mqtt
from paho.mqtt.enums import CallbackAPIVersion
broker = '127.0.0.1'
port = 7788
topic = "Htopic"
api=CallbackAPIVersion.VERSION2
# 连接的回调函数
def on_connect(client, userdata, flags,reason_code, rc):
print(f"Connected with result : {reason_code}")
client.subscribe(topic=topic)
# 收到消息的回调函数
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client(api)
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker, port, 60)
client.loop_forever()
发布者代码,文件名为pub.py
import paho.mqtt.client as mqtt
from paho.mqtt.enums import CallbackAPIVersion
import time
broker = '127.0.0.1'
port = 7788
topic = "Htopic"
api=CallbackAPIVersion.VERSION2
def on_connect(client, userdata, flags,reason_code, rc):
print(f"Connected with result code {rc}")
client = mqtt.Client(api)
client.on_connect = on_connect
client.connect(broker, port, 60)
for i in range(60):
client.publish(topic, payload=i, qos=0, retain=False)
print(f"send {i} to a/b{topic}")
time.sleep(1)
client.loop_forever()