React中使用MQTT协议,MQTT服务器配置
程序员文章站
2022-07-02 18:52:12
...
React MQTT使用
第一次接触MQTT的时候被这个错误耽误了好久,paho-mqtt.js:1054 WebSocket connection to ‘ws://192.168.1.61:1883/mqtt’ failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
本文简略介绍前端连接MQTT服务的基本用法,希望能帮到大家
1,安装
npm install paho-mqtt -s
2,初始化
const PahoMQTT = require('paho-mqtt')
const name = new Date().getTime() + 'client'
const client = new PahoMQTT.Client('192.168.1.61', 1884, name) // 服务器地址以及端口号
client.connect({
onSuccess: function (res) {
client.subscribe('offlineTopic') // 订阅频道
}
})
3,接受消息
client.onMessageArrived = onMessageArrived // 接收消息
function onMessageArrived(message) {
if (message.destinationName === 'offlineTopic') {
console.log(message.payloadString)
}
}
Ubantu 中安装测试mosquitto
1,引入mosquitto仓库并更新
sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
sudo apt-get update
2,执行以下命令安装mosquitto
sudo apt-get install mosquitto
3,查看mosquitto服务状态
sudo service mosquitto status
4,开启/停止mosquitto服务
sudo service mosquitto start
sudo service mosquitto stop
5,修改mosquitto配置文件
sudo vi /etc/mosquitto/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
listener 1883 # 新增
listener 1884 # 新增
protocol websockets # 新增
测试发布主题
mosquitto_pub -h 192.168.1.61 -t "mqtt" -m "Hello2 MQTT"
下一篇: python Web框架之Flask