react中MQTT的基础用法

news/2024/7/15 18:14:38 标签: react.js, javascript, 前端

MQTT是什么?

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

在react中如何使用?

1、安装MQTT

javascript">npm install mqtt --save
# or
yarn add mqtt

2、使用MQTT

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

(一)连接

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

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

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

(二)订阅

javascript"> 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}`)
      })
    }
  }

(三)取消订阅

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

(四)发布

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

(五)断开连接

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

3、react中使用完整代码

javascript">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


http://www.niftyadmin.cn/n/5261161.html

相关文章

祝贺 年citation突破100

有好多年,写不出1篇论文了,也没有思路,觉得做的内容非常浅,一直忙于实际应用项目,偏技术突破。 2018出国访学后,重新看文献,整理思路,拓展思维,逐步写了几篇论文&#x…

初识GroovyShell

文章目录 前言一、GroovyShell二、maven三、解决方案四、关键代码4.1 数据库配置表(pg)4.2 入参4.3 分页查询 总结 前言 项目背景:查询多个表的数据列表和详情,但不想创建过多的po、dao、resp等项目文件。 一、GroovyShell Apache Groovy是一种强大的…

异步导入中使用SecurityUtils.getSubject().getPrincipal()获取LoginUser对象导致的缓存删除失败问题

结论 SecurityUtils.getSubject().getPrincipal()实际用的也是ThreadLocal,而ThreadLocal和线程绑定,异步会导致存数据丢失,注意! 业务背景 最近,系统偶尔会出现excel导入成功,但系统却提示存在进行中的…

【数据结构】哈希经典应用:布隆过滤器(哈希+位图)——[深度解析](9)

前言 大家好吖,欢迎来到 YY 滴 数据结构 系列 ,热烈欢迎! 本章主要内容面向接触过C的老铁 主要内容含: 欢迎订阅 YY滴 数据结构 专栏!更多干货持续更新!以下是传送门! 目录 一.布隆过滤器产生的…

Kotlin(十六) 高阶函数的简单应用

高阶函数非常适用于简化各种API的调用,一些API的原有用法在使用高阶函数简化之后,不管是在易用性还是可读性方面,都可能会有很大的提升。 所以我们可以通过高阶函数来使一些API变得更简单更易读。在我们APP存储数据时,通常会用到…

flink yarn-session 启动失败retrying connect to server 0.0.0.0/0.0.0.0:8032

原因分析,启动yarn-session.sh,会向resourcemanager的端口8032发起请求: 但是一直无法请求到8032端口,触发重试机制会不断尝试 备注:此问题出现时,我的环境ambari部署的HA 高可用hadoop,三个节点…

二蛋赠书十一期:《TypeScript入门与区块链项目实战》

前言 大家好!我是二蛋,一个热爱技术、乐于分享的工程师。在过去的几年里,我一直通过各种渠道与大家分享技术知识和经验。我深知,每一位技术人员都对自己的技能提升和职业发展有着热切的期待。因此,我非常感激大家一直…

ODrive移植keil(九)—— 抗齿槽效应算法

目录 一、齿槽效应1.1、齿槽效应的定义1.2、产生原因1.3、解决办法 二、硬件接线三、ODrive官方代码操作3.1、固件版本v0.5.13.2、抗齿槽校准原理3.3、校准注意事项3.4、校准操作 四、移植后的代码操作五、总结 ODrive、VESC和SimpleFOC 教程链接汇总:请点击   一、…