在您的场景中,A设备通过路由器连接公网,B设备直接连接公网。为了测试A设备向B设备发送MQTT消息,可以按照以下步骤进行:
1. 确保MQTT Broker部署
- 如果A和B设备需要通过MQTT通信,需要一个MQTT Broker作为消息中转。
- 可以选择以下方式:
- 使用公共MQTT Broker(如
test.mosquitto.org
)。 - 在B设备上部署MQTT Broker(如 Mosquitto)。
- 在第三方服务器上部署MQTT Broker。
- 使用公共MQTT Broker(如
2. 配置路由器端口转发(如果需要)
- 如果MQTT Broker部署在B设备上,且B设备直接连接公网,A设备需要通过路由器的公网IP访问B设备。
- 如果B设备没有公网IP,需要在路由器上配置端口转发:
- 登录A设备所在的路由器管理界面。
- 添加端口转发规则:
- 外部端口:1883(MQTT默认端口)
- 内部IP:A设备的IP(
192.168.1.101
) - 内部端口:1883
- 协议:TCP
- 保存并应用设置。
3. 获取B设备的公网IP
- 如果B设备直接连接公网,获取其公网IP地址。
- 如果B设备的IP是私有IP(如
192.168.18.18
),则需要通过路由器配置端口转发或使用内网穿透工具(如 frp、ngrok)。
4. 在A设备上安装 mosquitto-clients
- 在A设备(Ubuntu)上安装MQTT客户端工具:
sudo apt update sudo apt install mosquitto-clients
5. 在B设备上安装并运行MQTT Broker
- 如果B设备需要运行MQTT Broker,可以安装 Mosquitto:
sudo apt update sudo apt install mosquitto
- 启动 Mosquitto Broker:
sudo systemctl start mosquitto sudo systemctl enable mosquitto
- 确保 Mosquitto 监听默认端口(1883)。
6. 在B设备上订阅主题
- 在B设备上使用
mosquitto_sub
订阅一个主题,等待接收消息:mosquitto_sub -h localhost -t test -v
- 如果B设备直接连接公网,可以使用其公网IP:
mosquitto_sub -h <B设备的公网IP> -t test -v
7. 在A设备上发布消息
- 在A设备上使用
mosquitto_pub
向B设备发送消息:mosquitto_pub -h <B设备的公网IP> -t test -m "Hello from A"
- 如果B设备运行了MQTT Broker,A设备需要将消息发送到B设备的公网IP。
8. 验证通信
- 如果配置正确,B设备的
mosquitto_sub
会显示接收到的消息:test Hello from A
9. 调试和排查问题
- 如果通信失败,检查以下内容:
- 网络连接:确保A设备可以访问B设备的公网IP。
- 端口转发:确保路由器端口转发规则正确。
- 防火墙:确保A设备和B设备的防火墙允许MQTT端口(1883)的流量。
- Broker配置:确保B设备的MQTT Broker已正确运行并监听指定端口。
10. 使用公共MQTT Broker测试(可选)
- 如果不想在B设备上部署MQTT Broker,可以使用公共Broker(如
test.mosquitto.org
)进行测试。 - 在A设备和B设备上分别运行以下命令:
- A设备发布消息:
mosquitto_pub -h test.mosquitto.org -t test -m "Hello from A"
- B设备订阅消息:
mosquitto_sub -h test.mosquitto.org -t test -v
- A设备发布消息:
通过以上步骤,您可以测试A设备向B设备发送MQTT消息。如果仍有问题,请检查网络配置或MQTT Broker日志以获取更多信息。