--
MQTT client library
推薦使用 MQTT.js 原因如下
--
MQTT.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>MQTT - WebSocket</title> <script src="mqtt.min.js"></script> </head> <body> <script> var options = { //mqtt客户端的id,这里面应该还可以加上其他参数,具体看官方文档 clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8), username: 'hoyo', password: 'hoyo' }; //浏览器采用websocket协议,host主机地址为192.168.0.200,端口为9001,路径为/mqtt var client = mqtt.connect( "ws://broker.emqx.io:8083/mqtt", options ); // you add a ws:// url here //建立连接 client.on('connect', function () { //订阅主题 presence client.subscribe('presence', function (err) { if (!err) { console.log("subscribe success!"); //发布主题presence,消息内容为Hello mqtt client.publish('presence', 'Hello mqtt') }else{ //打印错误 console.log(err) } }) }); //如果连接错误,打印错误 client.on('error', function (err) { console.log(err); client.end() }); //如果client订阅主题成功,那么这里就是当接收到自己订阅主题的处理逻辑 client.on('message', function (topic, message) { // message is Buffer,此处就是打印消息的具体内容 console.log(topic, message.toString()) }) </script> </body> </html> |
--
使用公共 MQTT Borker 搭建聊天室 - Eclipse Paho JavaScript Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>MQTT - WebSocket</title> <link rel="stylesheet" href="/3rdParty/bootstrap-4.3.1/css/bootstrap.min.css"> <script src="mqttws31.min.js"></script> <script src="/3rdParty/jquery-1.11.3.min.js"></script> </head> <body> <div id="chart_all"></div> <label style="position: fixed; bottom: 0;">留言:<input type="text" id="send" class="form-control" onkeyup="send()"></label> <script> function $_GET(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function time() { return Math.floor(new Date() .getTime() / 1000); } function send(){ if (event.keyCode === 13) { event.preventDefault(); event.stopPropagation(); message = new Paho.MQTT.Message('{"time":"'+ time() +'", "user":"'+ user +'", "talk":"'+$('#send').val()+'"}'); message.destinationName = "/HoyoMQTTChar/All"; client.send(message); $('#send').val(''); } } var user = $_GET('user'); client = new Paho.MQTT.Client('broker.emqx.io', Number(8083), user); // set callback handlers client.onConnectionLost = onConnectionLost; client.onMessageArrived = onMessageArrived; // connect the client client.connect({ onSuccess:onConnect, userName : "hoyo", password : "hoyo" }); // called when the client connects function onConnect() { // Once a connection has been made, make a subscription and send a message. console.log("onConnect"); client.subscribe("/HoyoMQTTChar/All"); } // called when the client loses its connection function onConnectionLost(r) { if (r.errorCode !== 0) { console.log("onConnectionLost:"+r.errorMessage); } } // called when a message arrives function onMessageArrived(m) { if ( m.destinationName ==='/HoyoMQTTChar/All' ){ var j = JSON.parse(m.payloadString); $('#chart_all').append('<div>'+ j.time +' <b>'+ j.user +'</b> : '+ j.talk +'</div>'); } } </script> </body> </html> |
結果
--
結論
- WebSocket 因為運作在瀏覽器上,因此不能將隱私或是系統安全洩漏,例如使用者帳號、密碼。也因為可以自訂訂閱主題的特性,為了避免遭到不當使用也要使用 ACL 過濾可供使用主題
- 在完全不寫 Borker 程式代碼的情況下,基本功能都無法實現,例如使用者清單,因為後一位使用者加入無法取得更早的使用者,也就是「舊資料」的提供只能從 Broker Server 端收集提供
--
1,231 total views, 3 views today