简体   繁体   中英

Implementing CoAP protocol on node.js

Do you know any guides or tutorials about implementing CoAP protocol connection on node.js? I have to implement simple server and client application. I've checked all the resources I've found, including of course their documentation:

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

but it is still unclear for me.

Thank you for any help.

EDIT:

If this is implementation of server, how should look client like?

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()
})

or like this , an example for coap client

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();

It should be like this:


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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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