H5 浏览器端实现rabbitmq 订阅发布

docoker -compose 安装rabbitmq
version: '3'
services:
  rabbitmq:
    container_name: rabbitmq
    image: rabbitmq:3-management
    ports:
      - "5672:5672"
      - "15672:15672"
      - "15675:15675"
      - "15674:15674"
      - "1883:1883"
    volumes:
      - ~/data/rabbitmq/data/:/var/lib/rabbitmq/
      - ~/data/rabbitmq/log/:/var/log/rabbitmq

启用mqtt web插件

rabbitmq-plugins enable rabbitmq_management rabbitmq_web_mqtt

html 客户端

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
    <title>Mqtt Websockets</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js" type="text/javascript"></script>

    <style type="text/css">
        .button {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 8px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
        }
    </style>
    <script type="text/javascript">
        // 工具类 日期函数
        function getFormatDate() {
            var date = new Date();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            var strHours = date.getHours();
            var strMinutes = date.getMinutes();
            var strSeconds = date.getSeconds();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            if (strHours >= 0 && strHours <= 9) {
                strHours = "0" + strHours;
            }
            if (strMinutes >= 0 && strMinutes <= 9) {
                strMinutes = "0" + strMinutes;
            }
            if (strSeconds >= 0 && strSeconds <= 9) {
                strSeconds = "0" + strSeconds;
            }
            return date.getFullYear() + "-" + month + "-" + strDate + " " + strHours + ":" + strMinutes + ":" + strSeconds;
        }
    </script>

    <script type="text/javascript">
        // RabbitMq 服务器IP地址或域名地址
        const host = '127.0.0.1';
        //WebSocket 协议服务端口,如果是走 HTTPS,设置443端口
        const port = 15675;
        //需要操作的 Topic,第一级父级 topic
        const topic = 'MIDDOL-TEST';
        //设备唯一id
        const clientId = "myclientid_" + parseInt(Math.random() * 10000, 10);
        //服务连接失败后重新尝试连接的时间间隔
        const reconnectTimeout = 10000;
        // RabbitMq 用户名密码,确保该用户可以访问mqtt资源权限
        const cleansession = true;
        // RabbitMq 用户名密码,确保该用户可以访问mqtt资源权限
        const username = 'guest';
        const password = 'guest';
        //是否走加密 HTTPS,如果走 HTTPS,设置为 true
        const useTLS = false;

        // MQTT 客户端引用对象
        let mqtt;

        function MQTTconnect() {
            mqtt = new Paho.MQTT.Client(host, port, "/ws", clientId);
            mqtt.onConnectionLost = onConnectionLost;
            mqtt.onMessageArrived = onMessageArrived;
            let options = {
                timeout: 3,
                keepAliveInterval: 60,
                mqttVersion: 4,
                cleanSession: cleansession,
                onSuccess: onConnect,
                onFailure: onFailure,
                useSSL: useTLS,
                userName: username,
                password: password
            };
            mqtt.connect(options);
        }

        // 连接服务器失败
        function onFailure(message) {
            console.log("onFailure : " + message);
            $("#arrivedDiv").append("<div style='color: red'> " + getFormatDate() + " onFailure : " + message.errorMessage + " </div>");
            setTimeout(MQTTconnect, reconnectTimeout);
        }

        // 连接上服务器
        function onConnect() {
            // 订阅某个主题
            mqtt.subscribe(topic, {qos: 0});
            // 订阅P2P主题
            mqtt.subscribe(topic + "/p2p/" + clientId, {qos: 0});

            // 发布主题消息
            let message = new Paho.MQTT.Message("Connect success, Hello mqtt!");
            // set topic
            message.destinationName = topic;
            mqtt.send(message);

            //发送 P2P 消息
            message = new Paho.MQTT.Message("Connect success, Hello mqtt P2P Msg!");
            // set topic
            message.destinationName = topic + "/p2p/" + clientId;
            mqtt.send(message);
        }

        // 未连接服务器
        function onConnectionLost(response) {
            console.log("onConnectionLost : " + response);
            setTimeout(MQTTconnect, reconnectTimeout);
        }

        // 接收到mqtt消息
        function onMessageArrived(message) {
            let topic = message.destinationName;
            let payload = message.payloadString;
            // console.log("recv msg : " + topic + "   " + payload);

            $("#arrivedDiv").append("<div> " + getFormatDate() + " recv msg : topic=" + topic + "  ,payload=" + payload + " </div>")
        }

        // MQTT 连接初始化
        MQTTconnect();

        // 发送测试
        function testMessageSend() {
            let msg = $("#testMessage").val();
            if (msg == null || msg === '') {
                $("#arrivedDiv").append("<div style='color: red'>请在文本框输入消息后点击发送按钮</div>")
                return;
            }
            // 发布主题消息
            //set body
            let message = new Paho.MQTT.Message(msg);
            // set topic
            message.destinationName = topic;
            mqtt.send(message);
        }

        function testMessageClean() {
            $("#arrivedDiv").html("<br/>");
        }

        $(function () {
            $("#myClientIdSpan").html("" + clientId);
        })

    </script>
</head>

<div style="margin-top: 30px;">
    <span>MQTT设备ID(clientId):</span><span id="myClientIdSpan" style="font-weight: bold;"></span>
    <br/><br/>
    <label style="font-weight: bold" for="testMessage">MQTT消息:</label>
    <input style="height: 25px; width: 180px;" maxlength="60" value="这是一条测试消息" id="testMessage"/>
    <button class="button" id="mySendBtn" onclick="testMessageSend()"> 点击发送</button>

    <button class="button" id="cleanSendBtn" onclick="testMessageClean()"> 清空日志</button>
</div>

<div style="margin-top: 30px">

    <div style="font-size: 20px;color: darkcyan"> 接收到的mqtt消息日志</div>
    <hr/>
    <div id="arrivedDiv" style="height:600px; width:1000px; overflow:scroll; background:#EEEEEE;">
        <br/>
    </div>

</div>
</html>


posted @ 2023-03-17 10:40  vx_guanchaoguo0  阅读(186)  评论(0编辑  收藏  举报