npm安装第三方模块:
npm install aedes mqtt
编写js代码:
const aedes = require('aedes')()
const server = require('net').createServer(aedes.handle)
const port = 1883
server.listen(port, () => {
console.log(`MQTT broker running on port ${port}`)
})
// 客户端连接事件
aedes.on('client', (client) => {
console.log(`Client connected: ${client.id}`)
})
// 客户端断开事件
aedes.on('clientDisconnect', (client) => {
console.log(`Client disconnected: ${client.id}`)
})
// 订阅事件
aedes.on('subscribe', (subscriptions, client) => {
console.log(`Client ${client.id} subscribed to:`, subscriptions.map(s => s.topic))
})
// 发布事件
aedes.on('publish', (packet, c