您的位置:首页 - 文章 - 随笔 - 正文

网页端连接MQTT

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="https://cdn.bootcss.com/paho-mqtt/1.0.2/mqttws31.min.js"></script>
    <script>
        client = new Paho.MQTT.Client("192.168.0.99", Number(61614), "websockets-test");//建立客户端实例
        client.connect({onSuccess:onConnect});//连接服务器并注册连接成功处理事件
            function onConnect() {
                console.log("onConnected");
                topic = 'smartroom'; //订阅的主题
                client.subscribe(topic);//订阅主题
                console.log("subscribed");
                //发送消息
            }
            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);
                console.log("主题:"+message.destinationName);
            }
    </script>
</body>
</html>

升级版

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui/css/layui.css"/>
    <style>
        .layui-layer-demo .layui-layer-title{
            background: #4b4b4b;
            color: #eeeeee;
        }
        .layui-layer-demo .layui-layer-content{
            padding: 10px;
            min-height: 100px;
            min-width: 150px;
        }
    </style>
</head>
<body>
<div class="layui-container">
    <form class="layui-form" action="javascript:void(0)">
        <div class="layui-form-item layui-form-text" style="padding-top: 100px">
            <label class="layui-form-label">发送消息</label>
            <div class="layui-input-block">
                <textarea name="desc" placeholder="请输入内容" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">发送</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>
<script src="https://cdn.bootcss.com/paho-mqtt/1.0.2/mqttws31.min.js"></script>
<script src="https://www.layuicdn.com/layui/layui.js"></script>
<!--您的Layui代码start-->
<script type="text/javascript">
    layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element'], function () {
        var $ = layui.jquery
            ,form = layui.form
            ,laydate = layui.laydate //日期
            , laypage = layui.laypage //分页
            , layer = layui.layer //弹层
            , table = layui.table //表格
            , carousel = layui.carousel //轮播
            , upload = layui.upload //上传
            , element = layui.element; //元素操作 等等...
        /*layer弹出一个示例*/
        layer.msg('Layui 框架支持');
        /*
         创建client
         url:127.0.0.1   端口:8083   订阅端口ID:websockets-test
         */
        client = new Paho.MQTT.Client("127.0.0.1", Number(8083), "websockets-test");//建立客户端实例
        // 连接mqtt服务器
        client.connect({onSuccess: onConnect});//连接服务器并注册连接成功处理事件
        //回调方法
        function onConnect() {
            console.log("连接成功");
            layer.msg('MQTT 连接成功');
            topic = 'smartroom'; //订阅的主题
            //订阅主题
            client.subscribe(topic);//订阅主题
            layer.msg('MQTT 订阅主题:smartroom 成功!"');
            console.log("订阅主题:smartroom 成功!");
        }
        // 设置监听回调
        client.onConnectionLost = onConnectionLost;//注册连接断开处理事件
        client.onMessageArrived = onMessageArrived;//注册消息接收处理事件
        function onConnectionLost(responseObject) {
            if (responseObject.errorCode !== 0) {
                // console.log("onConnectionLost:"+responseObject.errorMessage);
                console.log("连接已断开");
            }
        }
        function onMessageArrived(message) {
            var html='<div style="padding:20px;">' +message.payloadString+ '</div>';
            layer.open({
                title: '收到主题'+message.destinationName+'新消息',
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                closeBtn: 0, //不显示关闭按钮
                anim: 2,
                shadeClose: true, //开启遮罩关闭
                content: html
            });
            console.log("收到消息:" + message.payloadString);
            console.log("主题:" + message.destinationName);
        }
        //发送消息
        function sendMsg(msg) {
            //发布消息
            message = new Paho.MQTT.Message(msg);
            message.destinationName = "smartroom";
            client.send(message);
        }
        //监听提交
        form.on('submit(formDemo)', function(data){
           console.log(JSON.stringify(data))
            //发送消息
            sendMsg(data.field.desc)
            return false;
        });
    });
</script>
</body>
</html>

本文原创,作者:西决,其版权均为品创网络所有。如需转载,请注明出处:https://www.sxpcwlkj.com/htmlmqtt/

发表评论