需求是实时获取后端推送的数据 只收不发
import mqtt from "mqtt/dist/mqtt.min";
const option = {
keepalive: 5, //心跳时间,默认 60秒,设置 0 为禁用;
clientId: +new Date(), //客户端 ID
username: "xxx", //连接用户名(可选),
password: "xxx", //连接密码(可选),
protocolVersion: 4,
clean: true, //设置为 false 以在离线时接收 QoS 1 和 2 消息;
reconnectPeriod: 1000, //默认 1000 毫秒,两次重新连接之间的间隔,客户端 ID 重复、认证失败等客户端会重新连接;
connectTimeout: 8 * 1000, //默认 30 * 1000毫秒,收到 CONNACK 之前等待的时间,即连接超时时间;
will: {
//遗嘱消息,当客户端严重断开连接时,Broker 将自动发送的消息。 一般格式为:
topic: "WillMsg",
payload: "Connection Closed abnormally..!",
qos: 0,
retain: false,
},
};
this.client = mqtt.connect('ws://192.111.3.000:8083/mqtt', option);//端口尽量使用8083 http用ws https用wss 端口后加上/mqtt
先进行连接 再订阅主题
this.client.on("connect", () => {
// console.log("连接成功");
this.client.subscribe(//订阅主题
subjectArr,//可以是字符串跟数组 数组订阅多个主题
{ qos: 0 }
);
});
订阅成功后接收信息
this.client.on("message", (topic, message, packet) => {
// 这里有可能拿到的数据格式是Uint8Array格式,所以可以直接用toString转成字符串
const data = JSON.parse(message.toString());
// console.log("返回的数据:", data, topic);
});