电子说
学习前准备:
//构建MQTT CONNECT参数
let CMD = MQTTConnect.create()
.setClientIdentifier('Harvey鸿蒙') //客户端名字
.buildPacket()
//配置Socket并且完成连接
HarmonyOSSocket.get()
.socketCfg({
address: {
address: this.sec1IP + "." + this.sec2IP + "." + this.sec3IP + "." + this.sec4IP,
port: 1883
}
},
)
.connectCfg(CMD)
.connect()
let options: SubscribeTopicNameOptions[] = [
{ topicName: this.currentPublishTopicName} //主题名称
]
HarmonyOSSocket.get().subscribeTopic(options)
//构建MQTT PUBLISH参数
let publishConfig = MQTTPublish.create()
.setQoS(this.currentPublishQoS)
.setTopicName(this.currentPublishTopicName)
HarmonyOSSocket.get()
.publishCfg(publishConfig)
.sendMessageByString(this.inputMessage)
//错误信息
getContext().eventHub.on(MQTTCommon.EVENTHUB_MQTT_APP_ERROR_MSG, (value) = > {
this.errorMessage = value
})
//
getContext().eventHub.on(MQTTCommon.EVENTHUB_MQTT_CMD_STATUS_MSG, (msg) = > {
if (msg.action === 'connect') { //MQTT CONNECT结果消息
if (msg.value == 0) {
//成功
} else {
Prompt.showToast({ message: '连接失败' })
}
} else if (msg.action === 'close') {
//1. TCPSocket 关闭事件
//2. MQTT 断开命令已发送完毕
} else if (msg.action == 'subscribeack') {
//订阅主题结果
let packet = msg.value as MQTTPacketStruct
} else if (msg.action == 'unsubscribeack') {
//解除主题订阅结果
let packet = msg.value as MQTTPacketStruct
} else if (msg.action == 'publish-s-to-c') {
//收到服务端数据包,即 接收到消息
let packet = msg.value as MQTTPacketStruct
} else if (msg.action == 'publish-c-to-s') {
//客户端发送给服务端数据包
let packet = msg.value as MQTTPacketStruct
}
})
HarmonyOSSocket.get().disconnect()
审核编辑 黄宇
全部0条评论
快来发表一下你的评论吧 !