13397158231   jevian_ma@worldflying.cn

简单实用的nodejs的http server与mqtt client实现(nodejs版本)

2020-07-15 01:53:49

nodejs作为一切皆异步的始祖编程语言,其性能自然不必多说。http server也是做常用的开发工具,这里就写一段基于nodejs的http server代码。

另外,额外添加mqtt client的代码端。话不多说,上代码:

const http = require("http")
const process = require('child_process')
const mqtt = require('mqtt')

let mqttclient  = mqtt.connect('mqtt://localhost', {
    username: 'username',
    password: 'password',
    will: {
        topic: 'devicewill',
        payload: 'device disconnect',
        qos: 0,
        retain: false
    }
})

mqttclient.on('connect', function () {
    mqttclient.subscribe('presence', function (err) {
        if (err) {
            console.log(err)
        }
    })
})

mqttclient.on('message', function (topic, message) {
    let obj = JSON.parse(message.toString())
    if (obj.act === "/api/runcmd") {
        process.exec(obj.cmd, function(err, stdout, stderr) {
            if (err) {
                console.log(err, "launch cmd fail.")
            } else {
                console.log("launch cmd success.")
            }
        })
    }
})

function getbody (req) {
    return new Promise(function (resolve, reject) {
        let body = ''
        req.on("data", function(data) {
            body += data;
        })
        req.on("end", function () {
            resolve(body)
        })
    })
}

http.createServer(async function (req, res) {
    if (req.url === "/api/runcmd") {
        let body = await getbody(req)
        process.exec(body, function(err, stdout, stderr) {
            if (err) {
                console.log(err)
                res.writeHead(200, {"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"})
                res.end(JSON.stringify({
                    "errcode": -2,
                    "errmsg": "launch cmd fail."
                }))
            } else {
                res.writeHead(200, {"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"})
                res.end(JSON.stringify({
                    "errcode": 0
                }))
            }
        })
    } else {
        res.writeHead(200, {"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"})
        res.end(JSON.stringify({
            "errcode": -99,
            "errmsg": "unknown api"
        }))
    }
}).listen(80)


文章作者:沃航科技

优秀产品推荐:可编程网络IO控制器

上一篇:使用go语言实现的dns请求程序

下一篇:go语言写的简单的http server以及mqtt client

联系我们

  • 地址:武汉市东湖高新开发区光谷总部国际1栋2412室
  • QQ:932773931
  • 电话:027-59761089-806
  • 手机:13397158231
  • 邮箱:jevian_ma@worldflying.cn

关注公众号

扫码添加微信

沃航(武汉)科技有限公司版权所有

备案号:鄂ICP备16014230号-1

本网站由提供CDN加速/云存储服务