先上鏈接
流程:
var mqtt = require('mqtt')
var clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
var host = 'wss://localhost:3001/Mosca'
var options = {
keepalive: 10,
clientId: clientId,
protocolId: 'MQTT',
protocolVersion: 4,
clean: true,
reconnectPeriod: 1000,
connectTimeout: 30 * 1000,
will: {
topic: 'WillMsg',
payload: 'Connection Closed abnormally..!',
qos: 0,
retain: false
},
username: 'demo',
password: 'demo',
rejectUnauthorized: false
}
var client = mqtt.connect(host, options)
client.on('error', function (err) {
console.log(err)
client.end()
})
client.on('connect', function () {
console.log('client connected:' + clientId)
})
client.subscribe('topic', { qos: 0 })
client.publish('topic', 'wss secure connection demo...!', { qos: 0, retain: false })
client.on('message', function (topic, message, packet) {
console.log('Received Message:= ' + message.toString() + '\nOn topic:= ' + topic)
})
client.on('close', function () {
console.log(clientId + ' disconnected')
})
注意事項(xiàng)
客戶端的默認(rèn)端口是 8083 不是 1883
Protocol | Listen On | Max Clients | Current Clients |
---|---|---|---|
mqtt:wss | 8084 | 64 | 0 |
mqtt:ssl | 8883 | 1024 | 0 |
mqtt:ws | 8083 | 64 | 0 |
mqtt:tcp | 0.0.0.0:1883 | 102400 | 0 |
mqtt:tcp | 127.0.0.1:11883 | 102400 | 0 |
dashboard:http | 18083 | 512 | 4 |
出現(xiàn)無(wú)限連接是因?yàn)閿?shù)據(jù)沒有發(fā)送成功,于是會(huì)一直連接,直到連接成功。
Qos | 說(shuō)明 |
---|---|
0 | 已發(fā)送 |
1 | 服務(wù)端確認(rèn)收到 |
2 | 都確認(rèn)收到 |