物聯網系統與CoAP之Hello,World

物聯網系統與CoAP Hello,World

關於CoAP與物聯網系統咱們在上一篇中(ps:CoAP與物聯網系統)中作一個簡單的介紹,接着咱們便開始試試CoAP協議的應用javascript

CoAP應用

開始以前咱們需要能訪問coap://localhost/,因而咱們便需要安裝一個Firefox的插件Copper。html

Firefox Copper

下載地址: https://addons.mozilla.org/en-US/firefox/addon/copper-270430/java

做爲測試咱們可以訪問 coap://vs0.inf.ethz.ch:5683/node

Node CoAP

node-coap is a client and server library for CoAP modelled after the http module.git

Node-CoAP是一個客戶端和服務端的庫用於CoAP的模塊建模。github

建立一個package.json文件。加入咱們的庫npm

{
    "dependencies":{
        "coap": "0.7.2"
    }
}

接着運行json

npm install

就可以安裝好咱們的依賴瀏覽器

CoAP 演示樣例

因而咱們就可以建立這樣一個app.js文件app

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

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

server.listen(function() {
  console.log('server started')
})

接着運行

node app.js

咱們就可以在瀏覽器上訪問了,僅僅是現在什麼也沒有。 接着咱們再建立一個client端的js,並運行之

const coap  = require('coap') 
    , req   = coap.request('coap://localhost/World')

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

req.end()

就可以在console上輸出

Hello World

也就達到了咱們的目的,用CoAP協議建立一個服務,接着咱們應該用它建立不少其它的東西,如產生JSON數據,以及RESTful。

其它

物聯網系統CoAP版進行時

https://github.com/gmszone/iot-coap

相關文章
相關標籤/搜索