Web 连接 EMQX,并发布和订阅主题
Posted Himmelbleu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Web 连接 EMQX,并发布和订阅主题相关的知识,希望对你有一定的参考价值。
简单封装
npm install mqtt
# 或使用 pnpm
pnpm install mqtt
# 或使用 yarn
yar add mqtt
如果你的项目是 TS 项目,需要在 tsconfig.json 中添加 allowJs: true
字段。
// 导入类型
import type MqttClient from "mqtt";
// 导入 min.js,而非 mqtt
import * as mqtt from "mqtt/dist/mqtt.min.js";
export function connect(): MqttClient
const mqttClient = mqtt.connect("ws://localhost:8083/mqtt",
clean: false,
connectTimeout: 4000,
clientId: "webclient",
username: "webclient",
password: "123456"
);
return mqttClient;
// 开启
export function start(client: MqttClient, onMessage: (msg: string) => void)
// 连接之后订阅一个主题
client.on("connect", function ()
client.subscribe("command", function (err) );
);
// 收到 emqx 服务器发送的主题,调用回调函数并把消息带出去,注意消息需要调用 toString
client.on("message", function (topic, message)
console.log(JSON.parse(message.toString()));
onMessage(JSON.parse(message.toString()));
);
// 发布主题
export function publish(client: MqttClient, data: topic: string; msg: string )
client.publish(data.topic, data.msg);
在组件中使用
import connect, start, publish from "@/emqx-utils";
import onMounted from "vue";
const nowCGQState = ref();
const emqxClient = connect();
const mqttCommand = ref("Num1Ledon");
onMounted(() =>
start(emqxClient, msg => (nowCGQState.value = msg));
)
function pushCommand()
publish(emqxClient, topic: "command", msg: mqttCommand.value );
<template>
<el-input v-model="mqttCommand" />
<el-button @click="pushCommand">发送主题</el-button>
</template>
以上是关于Web 连接 EMQX,并发布和订阅主题的主要内容,如果未能解决你的问题,请参考以下文章