点我去Gitee
点我去Gitee

mqtt

mqtt.js

import * as mqtt from "mqtt"


const options = {//mqtt参数
  clean: true,
  connectTimeout: 4000,
  clientId: "mqtt" + Math.random().toString(16).substr(2, 8),
};

let clientMqtt//mqtt实例

// 链接
export const connectMqtt = () => {
  return new Promise((resolve, reject) => {
    if (!clientMqtt) {//如果没有clientMatt 说明还没链接  就链接一下
      clientMqtt = mqtt.connect("wss://xx.xx.xx.xx:xxxx", options);
      clientMqtt.on('error', (error) => {//不知道是都会自动重连
        console.log('mqtt连接失败了' + JSON.stringify(error))
        reject('链接失败')
      })

      clientMqtt.on("connect", () => {
        // console.log('链接成功了');
        resolve('链接成功')
      });
    } else {//如果已经存在clientMqtt,就说明已经链接成功
      // console.log('链接成功了');
      resolve('链接成功')
    }

    clientMqtt.on("message", (topic, message) => {//监听接受信息
      reciveMessage(topic, message.toString())
    });
  })

}

// 订阅  订阅了才能接受信息
export const subscribeMqtt = (topic) => {
  return new Promise((resolve, reject) => {
    clientMqtt.subscribe(topic, (err) => {
      if (err) {
        console.log('订阅失败了');
        reject('订阅失败')
      }
      else {
        // console.log('订阅成功了');
        resolve('订阅成功')
      }
    });
  })
}


// 发布
export const pubilshMqtt = (topic, message) => {
  return new Promise((resolve, reject) => {
    clientMqtt.publish(topic, message, (error) => {
      if (error) {
        console.log('发布信息失败了');
        reject('发布信息失败')
      }
      else {
        // console.log('发布信息成功了');
        resolve('发布信息成功')
      }
    })
  })
}

// 结束
export const endMqtt = () => {
  return new Promise((resolve, reject) => {
    if (clientMqtt) {
      clientMqtt.end((error) => {
        if (error) {
          console.log('关闭失败了');
          reject('关闭失败')
        }
        else {
          clientMqtt = null
          // console.log('关闭mqtt成功');
          resolve('关闭成功')
        }
      })
    }
  })
}


const reciveMessage = (topic, message) => {
  // console.log('接受信息成功', topic, message);
}

应用组件

import React, { Component } from 'react'
import { connectMqtt, pubilshMqtt, subscribeMqtt, endMqtt } from '../../utils/mqtt'

export default class Text extends Component {

  async componentDidMount() {
    // 链接
    await connectMqtt()
    // 订阅
    await subscribeMqtt('BIG')
    // 发布
    await pubilshMqtt('BIG', 'sdfsjdfjsd')
  }
  async componentWillUnmount() {
    // 关闭
    await endMqtt()
  }

  render() {
    return (
      <div>看控制台</div>
    )
  }
}

posted @ 2022-06-01 11:30  biuo  阅读(47)  评论(0编辑  收藏  举报