After adding JSON support to IoT Coap, it becomes very interesting, at least we can get the results we want. In the previous article we introduced some common tools--coap the command-line toolset.
COAP Client code example
Before we start we need to have a client-side code so that our server can return the correct data and parse
var coap = require (' Coap '); var requesturi = ' coap://localhost/'; var url = require (' URL '). Parse (RequestUri + ' id/1/'); cons Ole.log ("Request URL:" + url.href), var req = coap.request (URL), var bl = require (' bl '); Req.setheader ("Accept", "Applicati On/json "); Req.on (' Response ', function (res) { res.pipe (BL (function (err, data) { var json = json.parse (data); Console.log (JSON); });}); Req.end ();
The code is a bit too long, but the core is this sentence:
Req.setheader ("Accept", "Application/json");
In that case, we only need to judge on our service side,
if (req.headers[' Accept '] = = ' Application/json ') { //do something};
This will return the data. (Reprint reservation: Coap and the return JSON of the Internet of Things system)
CoAP Server-side code
Server-side code is relatively simple, judge
if (req.headers[' Accept '] = = ' Application/json ') { parse_url (req.url, function (result) { res.end (result); }); res.code = ' 2.05 '; }
Whether the request is in JSON format, and then returns a 205, which is the content, just then the design is to request a URL to return the corresponding data. Such as
coap://localhost/id/1/
At this point, the data with ID 1 should be requested, i.e.
[{id:1, Value: ' Is ID 1 ', sensors1:19, sensors2:20}]
and Parse_url just reads the corresponding data from the database.
function Parse_url (URL, callback) { var db = new Sqlite3. Database (config["db_name"]); var result = []; Db.all ("SELECT * from basic;", function (err, rows) { callback (json.stringify (rows))} )}
and it all shows up, it's a bit of a design, but it's almost there.