react中MQTT的基础用法

MQTT是什么?

MQTT基于发布/订阅范式的消息协议,工作在TCP/IP协议族上,是为硬件性能低下的远程设备以及网络状况糟糕的情况下而设计的发布/订阅消息协议,是一个基于客户端-服务端的消息发布/订阅传输协议。

在react中如何使用?

1、安装MQTT

npm install mqtt --save
# or
yarn add mqtt

2、使用MQTT

主要包含连接服务、订阅主题、取消订阅主题、给主题发布消息、断开连接服务
另外还有几个监听事件:监听连接、监听重连、监听连接错误、**监听订阅主题的消息**

(一)连接

1、通过webSoket连接
设置客户端ID、用户名及密码,客户端ID应当具有唯一性
1.1、用户名和密码问你的后端同事,不过我的同事没有设置(●’◡’●)
1.2、客户端ID唯一性的实现
1.2.1、使用随机数函数
const clientId = 'mqtt_client_' + Math.random().toString(16).substring(2, 8);
1.2.2、使用当前时间
const clientId = 'mqtt_client_' + new Date().getTime();
1.3、客户端与MQTT Broker建立连接
const client = mqtt.connect('ws://domainName:port/mqtt', {
  clientId,
  username,
  password,
  // ...other options
});
2、通过mqtt连接

这种方式与2.1方式的区别:建立连接时的协议

const client = mqtt.connect('mqtt://domainName:port', {
  clientId,
  username,
  password,
  // ...other options
});

(二)订阅

 handleSubscribe = (topic, qos) => {
    if (client) {
      // subscribe topic
      client.subscribe(topic, { qos }, (error) => {
        if (error) {
          console.log('Subscribe to topics error', error)
          return
        }
        console.log(`Subscribe to topics: ${topic}`)
      })
    }
  }

(三)取消订阅

handleUnsub = (topic, qos) => {
    if (client) {
      client.unsubscribe(topic, { qos }, (error) => {
        if (error) {
          console.log('Unsubscribe error', error)
          return
        }
        console.log(`unsubscribed topic: ${topic}`)
      })
    }
  }

(四)发布

handlePublish = (pubRecord) => {
    if (client) {
      const { topic, qos, payload } = pubRecord
      client.publish(topic, payload, { qos }, (error) => {
        if (error) {
          console.log('Publish error: ', error)
        }
      })
    }
  }

(五)断开连接

handleDisconnect = () => {
    if (client) {
      try {
        client.end(false, () => {
          console.log('disconnected successfully')
        })
      } catch (error) {
        console.log('disconnect error:', error)
      }
    }
  }

3、react中使用完整代码

import React from 'react'
import mqtt from 'mqtt'

class ClassMqtt extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      client: null,
      connectStatus: 'Connect',
      isSubed: false,
      messages: [],
    }
  }

  handleConnect = (host, mqttOptions) => {
    this.setState({ connectStatus: 'Connecting' })
    this.client = mqtt.connect(host, mqttOptions)

    if (this.client) {
      this.client.on('connect', () => {
        this.setState({ connectStatus: 'Connected' })
        console.log('connection successful')
      })

      this.client.on('error', (err) => {
        console.error('Connection error: ', err)
        this.client.end()
      })

      this.client.on('reconnect', () => {
        this.setState({ connectStatus: 'Reconnecting' })
      })

      this.client.on('message', (topic, message) => {
        const payload = { topic, message: message.toString() }
        const { messages } = this.state
        if (payload.topic) {
          const changedMessages = messages.concat([payload])
          this.setState({ messages: changedMessages })
        }
        console.log(`received message: ${message} from topic: ${topic}`)
      })
    }
  }

  handleSubscribe = (topic, qos) => {
    if (this.client) {
      // subscribe topic
      this.client.subscribe(topic, { qos }, (error) => {
        if (error) {
          console.log('Subscribe to topics error', error)
          return
        }
        console.log(`Subscribe to topics: ${topic}`)
        this.setState({ isSubed: true })
      })
    }
  }

  // unsubscribe topic
  handleUnsub = (topic, qos) => {
    if (this.client) {
      this.client.unsubscribe(topic, { qos }, (error) => {
        if (error) {
          console.log('Unsubscribe error', error)
          return
        }
        console.log(`unsubscribed topic: ${topic}`)
        this.setState({ isSubed: false })
      })
    }
  }

  // publish message
  handlePublish = (pubRecord) => {
    if (this.client) {
      const { topic, qos, payload } = pubRecord
      this.client.publish(topic, payload, { qos }, (error) => {
        if (error) {
          console.log('Publish error: ', error)
        }
      })
    }
  }

  // disconnect
  handleDisconnect = () => {
    if (this.client) {
      try {
        this.client.end(false, () => {
          this.setState({ connectStatus: 'Connect' })
          this.setState({ client: null })
          console.log('disconnected successfully')
        })
      } catch (error) {
        this.setState({ connectStatus: 'Connect' })
        console.log('disconnect error:', error)
      }
    }
  }

  render() {
    return (
      {/* jsx代码 */}
    )
  }
}

export default ClassMqtt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值