JavaScript使用MQTT

目录

1、安装MQTT服务器

2、启动emqx,woesocket

3、编写服务端(发布)

4、编写客户端(订阅接收)

5、效果展示


目的:前端接收mqtt消息,例如实时展示位置信息等。

1、安装MQTT服务器

可以使用网络提供的公共服务器也可以自建,例如这里安装EMQX。

下载 EMQX

输入emqx_ctl staus,出现以上说明已启动。 

2、 启动emqx,woesocket

输入本地emqx地址,例如http://127.0.0.1:18083/,打开websocket页面,确定好host,port等信息并启动,后续会用到这些信息。这实际上是个mqtt管理页面,后续连接到mqtt也能在该页面查看连接状态等信息。

3、编写服务端(发布)

这里用python写(实在是方便),语言不限。mqtt以及相关库自行安装。

#coding=utf-8
import paho.mqtt.client as mqtt
import random
import json

def on_connect(client,userdata,flags,rc):
    print("Connected with result code: "+str(rc))

def on_message(client,userdata,msg):
    print(msg.topic+" "+str(msg.payload))

client=mqtt.Client()
client.on_connect=on_connect
client.on_message=on_message
client.connect('你的ip',1883,600)

//这边模拟输出100个点位坐标(lon,lat,height)
for i in range(0,100):
    client.publish('你的topic',json.dumps({
    'lon':120+random.randint(0,2000)/2000,
    "lat":28+random.randint(0,2000)/2000,
    "height":random.randint(0,1000)/100
},ensure_ascii=False))

4、编写客户端(订阅接收)

 javascript编写客户端接受信息。

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

<script>

        var hostname = '你的ip', 
            port = 8083, //这里就是第二步配置的port
            clientId = 'client-test',
            timeout = 5,
            keepAlive = 100,
            cleanSession = false,
            ssl = false,
            topic = '你的tpic';
        client = new Paho.MQTT.Client(hostname, port, clientId);
        //建立客户端实例  
        var options = {
            invocationContext: {
                host: hostname,
                port: port,
                path: client.path,
                clientId: clientId
            },
            timeout: timeout,
            keepAliveInterval: keepAlive,
            cleanSession: cleanSession,
            useSSL: ssl,
            // userName: userName,  
            // password: password,  
            onSuccess: onConnect,
            onFailure: function (e) {
                console.log(e);
                s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onFailure()}";
                console.log(s);
            }
        };
        client.connect(options);
        //连接服务器并注册连接成功处理事件  
        function onConnect() {
            console.log("onConnected");
            s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnected()}";
            console.log(s);
            client.subscribe(topic);
        }

        client.onConnectionLost = onConnectionLost;

        //注册连接断开处理事件  
        client.onMessageArrived = onMessageArrived;

        //注册消息接收处理事件  
        function onConnectionLost(responseObject) {
            console.log(responseObject);
            s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnectionLost()}";
            console.log(s);
            if (responseObject.errorCode !== 0) {
                console.log("onConnectionLost:" + responseObject.errorMessage);
                console.log("连接已断开");
            }
        }

        function onMessageArrived(message) {
            s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onMessageArrived()}";
            console.log(s);
            console.log("收到消息:" + message.payloadString);
        }

        function send() {
            var s = document.getElementById("msg").value;
            if (s) {
                s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (s) + ", from: web console}";
                message = new Paho.MQTT.Message(s);
                message.destinationName = topic;
                client.send(message);
                document.getElementById("msg").value = "";
            }
        }

        var count = 0;

        function start() {
            window.tester = window.setInterval(function () {
                if (client.isConnected) {
                    var s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (count++) +
                        ", from: web console}";
                    message = new Paho.MQTT.Message(s);
                    message.destinationName = topic;
                    client.send(message);
                }
            }, 1000);
        }

        function stop() {
            window.clearInterval(window.tester);
        }

        Date.prototype.Format = function (fmt) { //author: meizz 
            var o = {
                "M+": this.getMonth() + 1, //月份 
                "d+": this.getDate(), //日 
                "h+": this.getHours(), //小时 
                "m+": this.getMinutes(), //分 
                "s+": this.getSeconds(), //秒 
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
                "S": this.getMilliseconds() //毫秒 
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[
                    k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
    </script>

5、效果展示

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
连接 MQTT 协议可以使用 Paho JavaScript 客户端库。在连接时,可以使用 Paho 客户端提供的自动重连功能,以便在连接丢失或断开时重新连接。 下面是使用 Paho JavaScript 客户端库连接 MQTT 协议并启用自动重连的示例代码: ```javascript // 创建客户端实例 var client = new Paho.MQTT.Client("mqtt.example.com", 1883, "clientId"); // 设置连接参数 var options = { useSSL: false, cleanSession: true, onSuccess: onConnect, onFailure: onFailure, reconnect: true, // 启用自动重连 reconnectInterval: 5000 // 重连间隔(毫秒) }; // 连接到 MQTT 服务器 client.connect(options); // 连接成功回调函数 function onConnect() { console.log("Connected to MQTT server!"); // 订阅一个主题 client.subscribe("topic"); } // 连接失败回调函数 function onFailure() { console.log("Failed to connect to MQTT server!"); } ``` 在上面的示例代码中,`reconnect` 参数设置为 `true`,以启用自动重连功能。当连接丢失或断开时,Paho 客户端将自动尝试重新连接。`reconnectInterval` 参数设置重新连接的间隔时间(以毫秒为单位)。 注意,自动重连功能可能会导致连接请求不断重试,直到连接成功或达到最大重试次数。为了避免无限制的重试,可以通过设置 `maxReconnectAttempts` 参数来控制最大重试次数。例如: ```javascript var options = { reconnect: true, reconnectInterval: 5000, maxReconnectAttempts: 10 // 最大重试次数 }; ``` 以上就是使用 JavaScript 连接 MQTT 协议并启用自动重连的示例代码。希望能对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LionelMessi7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值