標籤:coap json 物聯網
0 前言 本文說明如何使用node-coap返回JSON資料包。CoAP是專門為物聯網系統開發的面向網路的應用程式層協議棧,CoAP建立在UDP協議之上儘可能減少網路開銷,又具有HTTP Restful類型的特性。node-coap使用nodejs實現了coap的用戶端和伺服器端。 【測試環境】——ubuntu/Linux 【相關博文】
【CoAP協議文檔——The Constrained Application Protocol (CoAP)】 【CoAP協議學習——CoAP基礎】 【CoAP學習筆記——CoAP資摘要搜索】 【CoAP學習筆記——伺服器端繁忙時的處理請求流程】 【CoAP學習筆記——nodeJS node-coap安裝和使用(Linux平台)】 【CoAP學習筆記——nodeJS node-coap安裝和使用(windows平台)】 【樹莓派學習筆記——webiopi安裝與入門】webiopi中整合了CoAP Server,可以方便地通過CoAP協議控制樹莓派GPIO。
1 伺服器代碼
var coap = require('coap');var server = coap.createServer();server.on('request',function(req, res) { console.log(req.headers); // 要求標頭中必須包括application/json if (req.headers['Accept'] != 'application/json') { res.code = '4.06'; return res.end(); } res.setOption('Content-Format', 'application/json'); res.end(JSON.stringify({ hello: "world" }));});server.listen(function() { console.log('server started');}); 【簡單說明】 【1】req.headers[‘Accept‘] != ‘application/json‘ 由於返回JSON資料包,要求標頭中最好包括Accept: application/json 【2】res.setOption(‘Content-Format‘, ‘application/json‘); 設定回應標頭 【3】res.end(JSON.stringify({hello: "world"})); 返回JSON資料包,資料包為固定內容{"hello":"world"}
2 用戶端代碼
var coap = require('coap');var bl = require('bl');var req = coap.request({ pathname: '/', options: { 'Accept': 'application/json' }});req.on('response',function(res) { console.log('response code', res.code); if (res.code !== '2.05') return process.exit(1); res.pipe(bl(function(err, data) { var json = JSON.parse(data); console.log(json); process.exit(0); }))});req.end(); 【執行返回】response code 2.05
{ hello: ‘world‘ } 【簡要說明】 【1】var req = coap.request({pathname: ‘/‘, options: { ‘Accept‘: ‘application/json‘}}); 要求標頭中包括Accept: application/json。 3 瀏覽器測試 若要求標頭中沒有包括Accept: application/json,那麼伺服器返回4.06錯誤,相當於HTTP中的404。
圖1 返回錯誤結果 啟動Debug模式,設定Accept選項為application/json。
圖2 返回正確結果
4 wireshark抓包4.1 使用tcpdump工具sudo tcpdump -i lo -w ~/temp/coap-json.cap 【簡單說明】 【1】-i參數制定網卡,lo代表迴環
【2】-w制定輸出檔案路徑和檔案名稱,此處儲存在cap格式檔案
4.2 cap檔案匯入wireshark中
圖3 wireshark抓包5 總結 感覺CoAP協議還深入的不夠,協議本身還是需要花些時間整理消化。
CoAP學習筆記——nodeJS node-coap返回JSON資料包