代码拉取完成,页面将自动刷新
const mqtt = require('mqtt')
/***
* Browser
* Using MQTT over WebSocket with ws and wss protocols
* EMQX's ws connection default port is 8083, wss is 8084
* Note that you need to add a path after the connection address, such as /mqtt
*/
// const url = 'wss://broker.emqx.io:8084/mqtt'
/***
* Node.js
* Using MQTT over TCP with mqtt and mqtts protocols
* EMQX's mqtt connection default port is 1883, mqtts is 8883
*/
const url = 'mqtts://broker.emqx.io:8883'
// Create an MQTT client instance
const options = {
// Clean session
clean: true,
connectTimeout: 4000,
// Authentication
clientId: 'emqx_test',
username: 'emqx_test',
password: 'emqx_test',
rejectUnauthorized: true,
}
const client = mqtt.connect(url, options)
client.on('connect', function () {
console.log('Connected')
// Subscribe to a topic
client.subscribe('test', function (err) {
if (!err) {
// Publish a message to a topic
client.publish('test', 'Hello mqtt')
}
})
})
// Receive messages
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。