MQTT协议 Websocket JS客户端

来源:互联网 发布:当呼吸化为空气知乎 编辑:程序博客网 时间:2024/05/18 02:21

MQTT协议支持HTML5的Websocket客户端连接,只需要JS代码就能实现方便实时的通信,下面是实现步骤

1、引入JS文件

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

2、使用代码

下面为核心代码的截取

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);

3、效果展示

利用MQTT协议远程控制LED灯 http://www.llqqww.com/open/iot/ 


【转载请注明出处:http://blog.csdn.net/leytton/article/details/51896951


1 0
原创粉丝点击