Skip to main content

创建React项目并连接到mqtt broker

创建React项目并连接到mqtt broker

首先创建React项目

npx create-react-app mqtt-react

进入目录cd mqtt-react 安装mqtt依赖

yarn add mqtt

修改src/App.js如下

import logo from './logo.svg'
import './App.css'
import {connect} from 'mqtt'
import {useEffect} from 'react'

function App() {
useEffect(() => {
let client = connect('wss://mqttx.cn:8883/mqtt')
// 连接成功的回调方法
client.on('connect', function (connack) {
console.log(connack)
console.log('connected')
// 订阅主题
client.subscribe('test/topic', {qos: 1})
setInterval(function () {
// 发布消息
client.publish('test/topic', 'hello from browser: ' + new Date(), {qos: 1})
}, 3000)
})
// 收到消息打印到控制台
client.on('message', function (topic, payload, packet) {
console.log(topic, payload.toString('utf-8'), packet)
})
}, [])
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<p> Edit <code>src/App.js</code> and save to reload. </p>
<a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer">
Learn React
</a>
</header>
</div>
)
}

export default App