MQTT協議 Websocket JS客戶端

MQTT協議支持HTML5的Websocket客戶端鏈接,只須要JS代碼就能實現方便實時的通訊,下面是實現步驟javascript

一、引入JS文件

<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>

二、使用代碼

下面爲核心代碼的截取java

client = new Paho.MQTT.Client("服務器域名", Number(端口號), "客戶端ID");//創建客戶端實例
        client.connect({onSuccess:onConnect});//鏈接服務器並註冊鏈接成功處理事件
        function onConnect() {
	        console.log("onConnected");
	        client.subscribe("/topic_back");//訂閱主題
        }
        client.onConnectionLost = onConnectionLost;//註冊鏈接斷開處理事件
        client.onMessageArrived = onMessageArrived;//註冊消息接收處理事件
        function onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                console.log("onConnectionLost:"+responseObject.errorMessage);
                console.log("鏈接已斷開");
             }
        }
        function onMessageArrived(message) {
		  console.log("收到消息:"+message.payloadString);
		}
        //發送消息
        message = new Paho.MQTT.Message("hello");
		message.destinationName = "/topic";
		client.send(message);

三、代碼運行效果


注意:此處只做演示,發送消息應該放在onConnect函數內,確保鏈接成功再發送!

四、效果展現

利用MQTT協議遠程控制LED燈 http://www.llqqww.com/open/iot/ 
ajax


【轉載請註明出處:http://blog.csdn.net/leytton/article/details/51896951
服務器

相關文章
相關標籤/搜索