您好,登錄后才能下訂單哦!
這篇文章主要介紹“在JavaScript中使用mqtt.js的詳細過程”,在日常操作中,相信很多人在在JavaScript中使用mqtt.js的詳細過程問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”在JavaScript中使用mqtt.js的詳細過程”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
<!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) // 創建一個client 實例 let url = 'ws://' + host + ':' + port + '/mqtt' client = mqtt.connect(url) console.log(client) client.on('connect', onConnect) // 斷開連接以后觸發 client.on('close', () => { console.log('disconnected') }) // 收到斷開連接的報文后觸發 client.on('disconnect', packet => { console.log(packet) }) // 客戶端下線時觸發 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}`) }) }) // 當client連接時調用 function onConnect() { // 訂閱主題 client.subscribe('world', err => { if (!err) { // 發布消息 client.publish('world', 'hello mqtt') } }) } // 斷開連接 $('#disconnect').click(() => { console.log('disconnect'); client.end() }) // 發送消息 $('#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>
在
SprintBoot
項目中集成ActiveMQ
后,接收到的數據為字節數組
一種解決方式為:
@JmsListener(destination = "test_producer", containerFactory = "topicListenerContainer") public void receiveTestProducer(Message message) throws JMSException { String msg = StringUtils.activeMQMessageParse(message); System.out.println("收到測試生產者的消息: " + msg); } public class StringUtils { /** * 將字符串進行分割并獲得字節數組 * @param str 待處理字符串 * @param split 分割字符串 * @return 字節數組 */ 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; } /** * 根據字節數組獲取指定字符集的字符串 * @param byteArr 字節數組 * @param charset 編碼字符集 * @return 處理后的字符串 */ public static String bytesToString(byte[] byteArr, Charset charset) { return new String(byteArr, charset); } /** * 將字符串根據分隔符轉成字節數組,然后轉成指定字符集的字符串 * @param str 待處理字符串 * @param split 分割字符串 * @param charset 指定字符集 * @return 處理后的字符串 */ public static String stringToString(String str, String split, Charset charset) { return bytesToString(stringToBytes(str, split), charset); } /** * 將ActiveMQ接收到的消息轉換為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; } }
到此,關于“在JavaScript中使用mqtt.js的詳細過程”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。