Skip to main content

断开连接

当发送完消息或者不需要接收服务端消息的时候就可以考虑断开连接了,节省服务器资源。

签名是:client#end([force], [options], [callback])

3个参数都是可选的

  • force 如果设置为true ,那么不管有没有没有确认的消息,都会发送disconnect包
  • options mqtt 5才用到,本课程不讲mqtt 5
  • callback 客户端关闭之后会回调这个方法

示例代码:

app.js
import {
connect,
Buffer
} from './utils/mqtt.min'

App({
onLaunch() {
let client = connect({
protocol: 'wxs',
host: 'mqttx.cn',
port: 8883,
path: '/mqtt',
clientId: 'test',
keepalive: 5,
clean: false,
connectTimeout: 3000
})

client.on('reconnect', function () {
console.log('reconnect', arguments.length)
})

client.on('connect', function (connack) {
console.log('connected', connack.sessionPresent)

client.subscribe('test/topic', {
qos: 1
}, function (err) {
if (!err) {
client.publish('test/topic', Buffer.from([0x01, 0o02, 0x03]), {
qos: 1
})

client.unsubscribe(['test/topic'], function (err) {
console.log(err, arguments.length)
})

client.end()
}
})
})

client.on('message', function (topic, payload, packet) {
console.log(payload)
})
}
})