基於Mosca的服務端實現
Mosca簡介,Mosca基於node.js開發,特性引用自項目首頁介紹如下:
Features
- MQTT 3.1 and 3.1.1 compliant.
- QoS 0 and QoS 1.
- Various storage options for QoS 1 offline packets, and subscriptions.
- As fast as it is possible.
- Usable inside ANY other Node.js app.
- Supports Node.js v0.10 and v0.12.
- Supports io.js v1.x and v2.x and v3.x (please do not use v3.1.0)
需要特別說明的是Mosca並不支持Qos 2。
為什么選擇Mosca?首先基於node.js開發,上手難度相對較小,其次協議支持完整,除了不支持Qos 2,其它的基本都支持。持久化支持redis以及mongo。二次開發接口簡單。部署非常簡單,並且支持docker鏡像。
開發步驟
安裝Mosca
本文環境假設你已經安裝了node.js環境以及redis,我本機的環境如下:mac ox 10.11.2 node.js v0.12 redis最新版本。
Mosca項目托管地址:https://github.com/mcollina/mosca
官方wiki:https://github.com/mcollina/mosca/wiki
安裝非常簡單,源引自官方說明如下:
Standalone
1 |
npm install mosca bunyan -g |
Embedded
1 |
npm install mosca --save |
啟動腳本
官方給了一個簡單的例子,如下是我現在使用的測試代碼:
1 |
var mosca = require('mosca') |
二次開發
可以監聽的事件列表
clientConnected
: when a client is connected; the client is passed as a
parameter.clientDisconnecting
: when a client is being disconnected; the client is
passed as a parameter.clientDisconnected
: when a client is disconnected; the client is passed as
a parameter.published
: when a new message is published; the packet and the client are
passed as parameters.delivered
: when a client has sent back a puback for a published message; the packet and the client are
passed as parameters.subscribed
: when a client is subscribed to a topic; the topic and the
client are passed as parameters.unsubscribed
: when a client is unsubscribed to a topic; the topic and the
client are passed as parameters.
有了上面可以監聽到事件你就可以根據自己的業務進行相應的開發,攔截特定的事件並添加業務代碼
ascoltatore托管地址 https://github.com/mcollina/ascoltatori
高級參數設置可以參考 https://github.com/mcollina/mosca/wiki/Mosca-advanced-usage
權限驗證可以參考 https://github.com/mcollina/mosca/wiki/Authentication-&-Authorization
配置ssl可以參考 https://github.com/mcollina/mosca/wiki/TLS-SSL-Configuration
配置WebSocket可以參考 https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets
寫在最后
感謝Mosca的作者mcollina,Mosca非常強大,並且足夠簡單。下篇文章會介紹如何利用IOS和Android開源客戶端類庫與Mosca對接,敬請期待!
轉載: http://targe.me/2015/12/29/mqtt-second/