在node.js上实现CoAP协议

时间:2019-03-06 16:00:57

标签: javascript node.js coap

您知道有关在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()
})

2 个答案:

答案 0 :(得分:1)

或类似这样的示例,用于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();

答案 1 :(得分:0)

应该是这样的:


    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