mqtt的使用
(1)一般放于工具类文件夹utils:
import mqtt from 'mqtt'; import { ConfigManager } from 'utils/config'; export default { connect() { var mqttServer = ConfigManager.getAppConfig('mqttServer'); var client = mqtt.connect({ protocol: window.location.protocol === 'https:' ? 'wss' : 'ws', host: mqttServer.ip, hostname: mqttServer.ip, port: mqttServer.port, path: window.location.protocol === 'https:' ? '/mqtt' : '/', connectTimeout: 60 * 1000, }); client.on('connect', function () { console.log('连接MQTT服务成功!'); }); client.on('reconnect', function () { console.log('mqtt正在尝试重新连接...'); }); client.on('offline', function () { console.log('mqtt连接出错'); client.unsubscribe('0/#'); }); client.on('close', function () { console.log('MQTT服务成功关闭!'); }); return client; }, listen(client, cb, topic = '0/#', format = true) { client.subscribe(topic, function () { console.log('mqtt预订消息成功'); }); client.on('message', function (topic, message) { try { const json = message.toString(); cb(JSON.parse(json)); } catch (e) { console.error(e); } }); }, unsubscribe(client, topic = '0/#') { client.unsubscribe('0/#', function () { console.log('mqtt取消预订'); }); }, };
(2)页面中使用(react)
import mqttUtil from 'utils/mqtt-util';
// 临时存放mqtt推送的消息
const mqttAlarmListTemp = useRef<IGlobalAlarmItem[]>([]);
useEffect(() => { const mqttClient = mqttUtil.connect(); const topic = `global_alarm/message/${userInfo!.id}`; mqttUtil.listen( mqttClient, (data: IGlobalAlarmItem) => { data.uuid = uuidv4(); mqttAlarmListTemp.current.unshift(data); run(); }, topic, ); return () => { mqttUtil.unsubscribe(mqttClient, topic); }; }, []);