在JavaScript中使用mqtt.js的詳細(xì)過程
ActiveMQ使用(二):在JavaScript中使用mqtt.js
1. 環(huán)境準(zhǔn)備 jQuery-1.10
下載地址
:https://www.jsdelivr.com/package/npm/jquery-1.10.2?tab=files
mqtt.js 4.3.7
:下載地址
:https://www.jsdelivr.com/package/npm/mqtt
2. 相關(guān)代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="connect-input-box"> <label for="host">host:</label> <input type="text" name="host" placeholder="input host" value="127.0.0.1"><br> <label for="port">port:</label> <input type="text" name="port" placeholder="input port" value="61614"><br> <label for="clientId">client id:</label> <input type="text" name="clientId" placeholder="input client id"><br> <label for="userId">user id:</label> <input type="text" name="userId" placeholder="input user id" value="user"><br> <label for="password">password:</label> <input type="text" name="password" placeholder="input password" value="pass"><br> <label for="destination">destination:</label> <input type="text" name="destination" placeholder="input destination" value="world"><br> <button id="connect" type="submit">connect</button> <button id="disconnect" type="submit">disconnect</button> </div> <div class="log-box"> <p id="log-show"></p> </div> <div class="send-message-box"> <label for="topic">topic:</label> <input type="text" name="topic"><br> <label for="queue">queue:</label> <input type="text" name="queue"><br> <input type="text" name="message"><br> <button id="send">send</button> </div> <div class="subscribe-box"> <label for="subscribe-topic">subscribe-topic:</label> <input type="text" name="subscribe-topic"> <button id="subscribe">subscribe</button> </div> <div class="unsubscribe-box"> <label for="unsubscribe-topic"></label> <input type="text" name="unsubscribe-topic"> <button id="unsubscribe">unsubscribe</button> </div> <script src="plugins/jquery-1.10.1.js"></script> <script src="plugins/mqtt.min.js"></script> <script type="module"> $(() => { console.log('mqtt: ', mqtt) $('input[name="clientId"]').val("example-" + Math.floor(Math.random() * 10000)) if (!window.WebSocket) { console.log('不支持WebSocket') } else { } }) var client, destination $('#connect').click(() => { var host = $('input[name="host"]').val() var port = $('input[name="port"]').val() var clientId = $('input[name="clientId"]').val() var user = $('input[name="userId"]').val() var password = $('input[name="password"]').val() destination = $('input[name="destination"]').val() console.log(host) console.log(mqtt) // 創(chuàng)建一個(gè)client 實(shí)例 let url = 'ws://' + host + ':' + port + '/mqtt' client = mqtt.connect(url) console.log(client) client.on('connect', onConnect) // 斷開連接以后觸發(fā) client.on('close', () => { console.log('disconnected') }) // 收到斷開連接的報(bào)文后觸發(fā) client.on('disconnect', packet => { console.log(packet) }) // 客戶端下線時(shí)觸發(fā) client.on('offline', () => { console.log('offline') }) // 接收消息 client.on('message', (topic, payload, packet) => { // message is buffer console.log(`Topic: ${topic}, Message: ${payload.toString()}, QoS: ${packet.qos}`) }) }) // 當(dāng)client連接時(shí)調(diào)用 function onConnect() { // 訂閱主題 client.subscribe('world', err => { if (!err) { // 發(fā)布消息 client.publish('world', 'hello mqtt') } }) } // 斷開連接 $('#disconnect').click(() => { console.log('disconnect'); client.end() }) // 發(fā)送消息 $('#send').click(() => { console.log('send') let topic = $('input[name="topic"]').val() let payload = $('input[name="message"]').val() let options = { qos: 0, retain: false, properties: { payloadFormatIndicator: true } } client.publish(topic.toString(), payload, options, (err) => { if (err) { console.log(err) } else { console.log('published') } }) }) // 訂閱主題 $('#subscribe').click(() => { console.log('subscribe') let topic = $('input[name="subscribe-topic"]').val() client.subscribe(topic, {qos: 0}, (error, granted) => { if (error) { console.log(error) } else { console.log(`${granted[0].topic} was subscribed`) } }) }) // 取消訂閱主題 $('#unsubscribe').click(() => { console.log('unsubscribe') let topic = $('input[name="unsubscribe-topic"]').val() client.unsubscribe(topic, err => { if (err) { console.log(err) } else { console.log('unscribed') } }) }) </script> </body> </html>
3. 結(jié)果展示
3.1 連接
3.2 訂閱
3.3 發(fā)送消息
3.4 取消訂閱
3.5 斷開連接
4. 相關(guān)參考
https://www.jsdelivr.com/package/npm/mqtt
5. 注意
在
SprintBoot
項(xiàng)目中集成ActiveMQ
后,接收到的數(shù)據(jù)為字節(jié)數(shù)組
一種解決方式為:
@JmsListener(destination = "test_producer", containerFactory = "topicListenerContainer") public void receiveTestProducer(Message message) throws JMSException { String msg = StringUtils.activeMQMessageParse(message); System.out.println("收到測(cè)試生產(chǎn)者的消息: " + msg); } public class StringUtils { /** * 將字符串進(jìn)行分割并獲得字節(jié)數(shù)組 * @param str 待處理字符串 * @param split 分割字符串 * @return 字節(jié)數(shù)組 */ public static byte[] stringToBytes(String str, String split) { String[] strArr = str.split(split); byte[] byteArr = new byte[strArr.length]; for (int i = 0; i < strArr.length; i++) { byteArr[i] = (byte) Integer.parseInt(strArr[i]); } return byteArr; } /** * 根據(jù)字節(jié)數(shù)組獲取指定字符集的字符串 * @param byteArr 字節(jié)數(shù)組 * @param charset 編碼字符集 * @return 處理后的字符串 */ public static String bytesToString(byte[] byteArr, Charset charset) { return new String(byteArr, charset); } /** * 將字符串根據(jù)分隔符轉(zhuǎn)成字節(jié)數(shù)組,然后轉(zhuǎn)成指定字符集的字符串 * @param str 待處理字符串 * @param split 分割字符串 * @param charset 指定字符集 * @return 處理后的字符串 */ public static String stringToString(String str, String split, Charset charset) { return bytesToString(stringToBytes(str, split), charset); } /** * 將ActiveMQ接收到的消息轉(zhuǎn)換為UTF-8字符串 * @param message * @return */ public static String activeMQMessageParse(Message message) { String str = null; if (message instanceof ActiveMQTextMessage) { ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message; try { str = textMessage.getText().toString(); } catch (JMSException e) { e.printStackTrace(); } // System.out.println("text : " + textMessage.getText()); } else if (message instanceof ActiveMQBytesMessage) { ActiveMQBytesMessage bytesMessage = (ActiveMQBytesMessage) message; byte[] byteArr = new byte[0]; try { byteArr = new byte[(int) bytesMessage.getBodyLength()]; int flag = bytesMessage.readBytes(byteArr); str = bytesToString(byteArr, StandardCharsets.UTF_8); // System.out.println("bytes : " + flag + " : " + str); } catch (JMSException e) { e.printStackTrace(); } } return str; } }
到此這篇關(guān)于在JavaScript中使用mqtt.js的文章就介紹到這了,更多相關(guān)js使用mqtt.js內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
layui中select,radio設(shè)置不生效的解決方法
今天小編就為大家分享一篇layui中select,radio設(shè)置不生效的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-09-09checkbox全選所涉及到的知識(shí)點(diǎn)介紹
checkbox全選涉及到的知識(shí)點(diǎn)比如IE里起作用,火狐不起作用,getElementById()與getElementsByName()的區(qū)別等等2013-12-12在Javascript中為String對(duì)象添加trim,ltrim,rtrim方法
利用Javascript中每個(gè)對(duì)象(Object)的prototype屬性我們可以為Javascript中的內(nèi)置對(duì)象添加我們自己的方法和屬性。2006-09-09JS 頁(yè)面內(nèi)容搜索,類似于 Ctrl+F功能的實(shí)現(xiàn)代碼
JS 頁(yè)面內(nèi)容搜索,類似于 Ctrl+F功能的實(shí)現(xiàn)代碼...2007-08-08JS中JSON.stringify使用場(chǎng)景面試精講
這篇文章主要為大家介紹了JS中JSON.stringify使用場(chǎng)景面試精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10javascript游戲開發(fā)之《三國(guó)志曹操傳》零部件開發(fā)(四)用地圖塊拼成大地圖
小時(shí)候我們玩過拼圖游戲,是用自己的手去拼的。今天我們來研究研究用javascript來拼圖感興趣的朋友可以了解下,希望本文對(duì)你有所幫助2013-01-01利用types增強(qiáng)vscode中js代碼提示功能詳解
這篇文章主要給大家介紹了如何增強(qiáng)vscode中js代碼提示功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編一起來學(xué)習(xí)學(xué)習(xí)吧。2017-07-07JavaScript網(wǎng)絡(luò)請(qǐng)求工具庫(kù)axios使用實(shí)例探索
這篇文章主要為大家介紹了JavaScript網(wǎng)絡(luò)請(qǐng)求工具庫(kù)axios使用實(shí)例探索,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01