使用Vue连接Mqtt实现主题的订阅及消息发布

效果如下:
在这里插入图片描述
直接贴代码,本地创建一个html文件将以下内容贴入即可

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT 客户端</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
	<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }
        h2 {
            margin-top: 20px;
        }
        form, .controls {
            margin-bottom: 20px;
        }
        .button {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .message-area {
            width: 100%;
            height: 300px;
            resize: none;
        }
    </style>
</head>
<body>
    <div id="app">
        <h2>MQTT服务器设置</h2>
        <form>
            <div class="controls">
                <label for="host">服务器地址:</label>
                <input type="text" v-model="host" id="host" placeholder="ws://broker.emqx.io">
                <label for="port">服务器端口:</label>
                <input type="text" v-model="port" id="port" placeholder="8083">
            </div>
            <div class="controls">
                <label for="path">服务器路径:</label>
                <input type="text" v-model="path" id="path" placeholder="/mqtt">
                <label for="clientID">客户端ID:</label>
                <input type="text" v-model="clientID" id="clientID" placeholder="随机生成">
            </div>
            <div class="controls">
                <label for="user">用户名:</label>
                <input type="text" v-model="user" id="user" placeholder="test">
                <label for="password">密码:</label>
                <input type="text" v-model="password" id="password" placeholder="123">
            </div>
        </form>
        <button class="button" @click="connectMQTT" :disabled="connected">连接</button>
        <button class="button" @click="connectEND" :disabled="!connected">已断开</button>

        <h2>MQTT订阅</h2>
        <div class="controls">
            <label for="subtopic">主题:</label>
            <input type="text" v-model="subtopic" id="subtopic" placeholder="test">
        </div>
        <button class="button" @click="subscribe_topic">订阅</button>

        <h2>MQTT消息发送</h2>
        <div class="controls">
            <label for="topic">主题:</label>
            <input type="text" v-model="topic" id="topic" placeholder="test">
            <label for="message">消息:</label>
            <input type="text" v-model="message" id="message" placeholder="test">
        </div>
        <button class="button" @click="sendMessage">发送</button>

        <h1>消息框</h1>
        <textarea class="message-area" id="messageTextArea" v-model="messageText" readonly></textarea>
    </div>

    <script>
        new Vue({
            el: '#app',
            data: {
                host: '',
                port: '8083',
                path: '/mqtt',
                clientID: '',
                user: 'test',
                password: 'test',
                connected: false,
                subtopic: 'test',
                topic: 'test',
                message: 'test',
                messageText: ''
            },
            methods: {
                connectMQTT() {
                    var url = this.host + ':' + this.port + this.path;
                    var options = {
                        clientId: this.clientID || this.randomID(),
                        username: this.user,
                        password: this.password
                    };
                    this.client = mqtt.connect(url, options);
                    this.client.on('connect', () => {
                        this.connected = true;
                        this.client.on('message', this.message_str);
                        this.messageText += '已连接\n';
                    });
                    this.client.stream.on('error', (err) => {
                        console.error('Connection error:', err);
                        this.connectEND();
                    });
                },
                connectEND() {
                    if (this.client && this.client.connected) {
                        this.client.end();
                        this.connected = false;
                        this.messageText += '已断开\n';
                    }
                },
                sendMessage() {
                    if (this.client && this.client.connected) {
                        this.client.publish(this.topic, this.message);
                        this.messageText += '已发送\n';
                    }
                },
                subscribe_topic() {
                    if (this.client && this.client.connected) {
                        this.client.subscribe(this.subtopic);
                        this.messageText += '已订阅' + this.subtopic + '\n';
                    }
                },
                message_str(topic, message) {
                    this.messageText += '收到来自主题:' + topic + '的消息:' + message.toString() + '\n';
                },
                randomID() {
                    return 'clientID_' + Math.random().toString(16).substr(2, 8);
                }
            }
        });
    </script>
</body>
</html>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue使用 MQTT,一般需要安装 `paho-mqtt` 库。可以通过 `npm` 进行安装: ``` npm install paho-mqtt --save ``` 接下来,我们可以在 Vue 的组件中使用 `paho-mqtt` 库进行 MQTT发布订阅。 首先,需要创建一个 MQTT 的客户端连接对象,可以在 Vue 组件的 `created` 生命周期中进行创建: ```javascript created() { // 创建 MQTT 客户端连接对象 this.client = new Paho.MQTT.Client("localhost", 8000, "clientId"); // 连接服务器 this.client.connect({ onSuccess: this.onConnect }); }, ``` 其中,`Paho.MQTT.Client` 是 `paho-mqtt` 库提供的 MQTT 客户端连接对象。它的构造函数需要传入三个参数: - `host`:MQTT 服务器的主机名或 IP 地址; - `port`:MQTT 服务器的端口号; - `clientId`:客户端 ID。 接下来,我们可以在 `onConnect` 回调函数中订阅 MQTT 主题: ```javascript onConnect() { // 订阅主题 this.client.subscribe("testTopic"); }, ``` 其中,`this.client.subscribe` 方法用于订阅 MQTT 主题,需要传入一个主题名称作为参数。 当客户端收到 MQTT 消息时,会触发 `onMessageArrived` 回调函数。可以在该函数中处理接收到的消息: ```javascript onMessageArrived(message) { console.log("Received message:", message.payloadString); }, ``` 最后,我们可以在 Vue 组件中定义发布消息的方法: ```javascript methods: { // 发布消息 publishMessage() { const message = new Paho.MQTT.Message("Hello, MQTT!"); message.destinationName = "testTopic"; this.client.send(message); }, }, ``` 其中,`Paho.MQTT.Message` 是 `paho-mqtt` 库提供的 MQTT 消息对象。它的构造函数需要传入一个字符串作为消息内容。接着,我们需要为消息设置目标主题,然后通过 `this.client.send` 方法将消息发送出去。 完整的代码示例如下: ```javascript <template> <div> <button @click="publishMessage">发布消息</button> </div> </template> <script> import Paho from "paho-mqtt"; export default { data() { return { client: null, }; }, created() { // 创建 MQTT 客户端连接对象 this.client = new Paho.MQTT.Client("localhost", 8000, "clientId"); // 连接服务器 this.client.connect({ onSuccess: this.onConnect }); }, methods: { // MQTT 连接成功回调函数 onConnect() { // 订阅主题 this.client.subscribe("testTopic"); }, // MQTT 收到消息回调函数 onMessageArrived(message) { console.log("Received message:", message.payloadString); }, // 发布消息 publishMessage() { const message = new Paho.MQTT.Message("Hello, MQTT!"); message.destinationName = "testTopic"; this.client.send(message); }, }, mounted() { // 注册 MQTT 消息接收回调函数 this.client.onMessageArrived = this.onMessageArrived; }, }; </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值