繁体   English   中英

在 node.js 上实现 CoAP 协议

[英]Implementing CoAP protocol on node.js

你知道关于在 node.js 上实现 CoAP 协议连接的任何指南或教程吗? 我必须实现简单的服务器和客户端应用程序。 我检查了我找到的所有资源,当然包括他们的文档:

https://github.com/mcollina/node-coap

但对我来说还不清楚。

感谢您的任何帮助。

编辑:

如果这是服务器的实现,客户端应该是什么样子的?

var coap        = require('coap')
  , server      = coap.createServer()

server.on('request', function(req, res) {
  res.end('Hello ' + req.url.split('/')[1] + '\n')
})

// the default CoAP port is 5683
server.listen(function() {
  var req = coap.request('coap://localhost/Matteo')

  req.on('response', function(res) {
    res.pipe(process.stdout)
    res.on('end', function() {
      process.exit(0)
    })
  })

  req.end()
})

或者像这样,coap客户端的一个例子

const coap = require('coap'),
  bl = require('bl');


//construct coap request
var req = coap.request({

  observe: false,
  host: '192.168.0.93',
  pathname: '/',
  port: 5683,
  method: 'get',
  confirmable: 'true',
  retrySend: 'true',
  //query:'',
  options: {
    //  "Content-Format": 'application/json'
  }

})

//put payload into request      
var payload = {
  username: 'aniu',
}
req.write(JSON.stringify(payload));

//waiting for coap server send con response
req.on('response', function(res) {
  //print response code, headers,options,method
  console.log('response code', res.code);

  if (res.code !== '2.05') return process.exit(1);
  //get response/payload from coap server, server sends json format
  res.pipe(bl(function(err, data) {
    //parse data into string
    var json = JSON.parse(data);
    console.log("string:", json);
    // JSON.stringify(json));
  }))

});
req.end();

应该是这样的:


    const coap = require('coap')
        req = coap.request('coap://localhost')
        console.log("Client Request...")

    req.on('response' , function(res){
            res.pipe(process.stdout)
        })
    req.end()

来源: https : //github.com/mcollina/node-coap/blob/master/examples/client.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM