2022-11-11 来源:华纳网 责任编辑:谷雨老师 人气:
核心提示:大家好,欢迎来到谷雨课堂 本节, 我们使用NodeJS来搭建MQTT服务器, 中小应用直接使用,无需再安装其它软件 以下是全部核心源代码 //No.45 使用NodeJS搭建MQTT服务器 const aedes = require ( aedes )() const server = require ( net ).createServer(aedes
大家好,欢迎来到谷雨课堂


本节,
我们使用NodeJS来搭建MQTT服务器,
中小应用直接使用,无需再安装其它软件
 
以下是全部核心源代码
 
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
//No.45 使用NodeJS搭建MQTT服务器
const aedes = require('aedes')()const server = require('net').createServer(aedes.handle)const port=1885
server.listen(port, function () {    console.log('Ys MQTT Server listening on port:', port)})
aedes.on('subscribe', function (subscriptions, client) {    console.log('MQTT client \x1b[32m' + (client ? client.id : client) +        '新订阅: ' + subscriptions.map(s => s.topic).join('\n'), 'from broker', aedes.id)})
aedes.on('unsubscribe', function (subscriptions, client) {    console.log('MQTT client \x1b[32m' + (client ? client.id : client) +        '取消订阅: ' + subscriptions.join('\n'), 'from broker', aedes.id)})
// fired when a client connectsaedes.on('client', function (client) {    console.log('客户端新连接: \x1b[33m' + (client ? client.id : client) + '\x1b[0m', 'to broker', aedes.id)})
// fired when a client disconnectsaedes.on('clientDisconnect', function (client) {    console.log('客户端断开: \x1b[31m' + (client ? client.id : client) + '\x1b[0m', 'to broker', aedes.id)})
// fired when a message is publishedaedes.on('publish', async function (packet, client) {    let topic=packet.topic    let payload=packet.payload.toString()    console.log('Client \x1b[31m' + (client ? client.id : 'BROKER_' + aedes.id) + '\x1b[0m 发布消息', packet.payload.toString(), 'on', packet.topic, 'to broker', aedes.id)})

 

 

 

完整的源代码可以登录【华纳网】下载。
https://www.worldwarner.com/






 





免责声明:本文仅代表作者个人观点,与华纳网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。