准備:首先去官網下載 HiveMQ 服務端
參考鏈接:https://www.hivemq.com/docs/hivemq/4.7/user-guide/install-hivemq.html#windows
我還在網上找個一個MQTT的可視化 客戶端 Paho : http://wiki.eclipse.org/Paho
將上面兩個文件解壓備用
以上准備工作各位看官自行下載
1、修改hiveMQ的cofig.文件如下圖一和圖二
圖一
圖二
2、寫前端demo 需要引用
CDN引入
具體如下
<!doctype html> <html lang="en"> <head> <title>Paho MQTT.js </title> <!-- 引用MQTT的CDN --> <script src="https://cdn.bootcss.com/paho-mqtt/1.0.2/mqttws31.min.js"></script> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script> <script src="https://cdn.jsdelivr.net/npm/echarts@5.3.1/dist/echarts.min.js"></script> </head> <body> <div id="main" style="width: 1800px;height:600px;"></div> <!-- 相關業務代碼 --> <script src="./index.js"></script> </body> </html>
var myChart = echarts.init(document.getElementById('main')); option1 = { title: { text: 'Stacked Line' }, tooltip: { trigger: 'axis' }, legend: { data: ['Email'] }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, toolbox: { feature: { saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { name: 'Email', type: 'line', stack: 'Total', data: [120, 132, 101, 134, 90, 230, 210] } ] }; myChart.setOption(option1); client = new Paho.MQTT.Client("192.168.20.101", Number(8000), "/mqtt","paho-21235228571500");//建立客戶端實例 其中 paho-21235228571500 為 客戶端 客戶機訂閱標識 client.connect({onSuccess:onConnect});//連接服務器並注冊連接成功處理事件 function onConnect() { console.log("onConnected"); topic = 'test'; //訂閱的主題 client.subscribe(topic);//訂閱主題 console.log("subscribed"); //發送消息 } client.onConnectionLost = onConnectionLost;//注冊連接斷開處理事件 client.onMessageArrived = onMessageArrived;//注冊消息接收處理事件 function onConnectionLost(responseObject) { if (responseObject.errorCode !== 0) { console.log("onConnectionLost:"+responseObject.errorMessage); console.log("連接已斷開"); } } function onMessageArrived(message) { var temp1 = jQuery.parseJSON(message.payloadString); console.log(temp1) option1.series[0].data=temp1; // 使用剛指定的配置項和數據顯示圖表。 myChart.setOption(option1); }
3、利用我們的Paho 工具發布一條數據 就會實時推送到前端 如下圖