0%

Mosca 介绍

Mosca 是 mqtt 协议 js 实现的一个包。

Mosca的作用:

  1. 与客户端建立长连接
  2. 作为代理服务器
  3. 根据发布订阅这模式,响应功能

    Mosca本身不做逻辑操作,一切的逻辑都放到他代理触发的事件中去执行

    比如:
1
2
3
4
5
6
let server = new protocolMosca.Server(settings)

server.on('clientConnected', (client) => {
function1()
console.log('client connected', client.id)
})

这里的 function1()就可以是外部引入的一个方法,把逻辑全部放到这个方法里去做

Mosca 的事件,每一个被触发时都会存储数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"_id": ObjectId("5b0d0f2a7bc72238259414b6"),
"value": BinData(0, "MTc="),
"topic": "temperature",
"options": {
"qos": 0,
"messageId": "oc6MQ_z",
"clientId": "mqttjs_acb34ce1"
}
}

{
"_id": ObjectId("5b0d0f81e5a65238e7705d27"),
"value": "mqttjs_acb34ce1",
"topic": "$SYS/Yt4U9fd/disconnect/clients",
"options": {
"qos": null,
"messageId": "G7ijrko"
}
}

如果是触发事件,会在 topic 里写事件名,否则就是某个packet.topic client 的订阅事件名.

事件种类如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/********************************************************************
*
* client about things of connect
* 1. clientConnected - when a cient is connected
* 2. clientDisconnecting - when a client is being disconnected
* 3. clientDisconnected - when a client is disconnected
* 4. clientError - when the server identifies a client connection error
/********************************************************************/

server.on('clientConnected', function (client) {
console.log('client connected', client.id)
})

server.on('clientDisconnecting', function (client) {
console.log('client client disconnecting', client.id)
})

server.on('clientDisconnected', function (client) {
console.log('client is disconnected', client.id)
})

server.on('clientError', function (client) {
console.log('client identifies error', client.id)
})

/********************************************************************
*
* client about published and subscribed
* 1. published - when a new message is published
* 2. subscribed - when a client is subscribed to a topic
* 3. unsubscribed - when a client is unsubscribed to a topic
/********************************************************************/

server.on('published', function (packet, client) {
console.log('Published Topic', packet.topic)
console.log('Published Payload', packet.payload.toString())
})

server.on('subscribed', async (topic) => {
let ret = await moscaHandle(topic, 100)
console.log('Subscribed', topic, ret)
})

server.on('unsubscribed', function (topic) {
console.log('Ubsubscribed', topic)
})

server.on('ready', function () {
console.log('server is running')
})

Mosca 的 setting

1
2
3
4
5
6
7
8
9
const settings = {
port: confAddress.port, // mosca 服务的端口号
backend: {
type: 'mongo',
url: 'mongodb://localhost:27017/mqtt',
pubsubCollection: 'mqtt201805',
mongo: {}
} // 数据存储的方式,这里不仅可以用 mongodb 也可以用 MySQL, redis 等等
}