You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MQTT.js订阅客户端无法接收publisher发送的userProperties问题

解决MQTT.js无法接收userProperties的问题

问题核心是MQTT.js默认使用MQTT 3.1.1协议,而userProperties是MQTT 5.0专属属性,必须显式指定协议版本为5才能支持该特性。

修改步骤

在发布端和订阅端的连接配置中,添加protocolVersion: 5字段:

发布端修改后的代码

import { connect } from "mqtt";

const connectOptions = {
  host: 'hive cloud',
  port: 8883,
  protocol: 'mqtts',
  username: 'username',
  password: 'password',
  protocolVersion: 5 // 指定使用MQTT 5协议
}
let client = connect(connectOptions)

client.on("connect", (connack) => {
  console.log("client connected", connack);
})

setInterval(() => {
  const payload = {1: "Hello world", 3: "Welcome to the test connection"}
  const publishOption = {
    qos: 1,
    retain: false,
    properties: {
      userProperties: {
        user: 'property'
      }
    }
  }
  client.publish('test/connection708', JSON.stringify(payload), publishOption)
}, 5000)

订阅端修改后的代码

import { connect } from "mqtt";

const connectOptions = {
  host: 'hive cloud',
  port: 8883,
  protocol: 'mqtts',
  username: 'username',
  password: 'password',
  protocolVersion: 5 // 指定使用MQTT 5协议
}

const topicName = 'test/connection708'

export let client = connect(connectOptions)

client.on('connect', (connack) => {
    console.log(connack)
    client.subscribe(topicName, (err, granted) => {
        if (err) {
            console.log(err, 'err')
        }
        console.log(granted, 'granted')
    })
})

client.on('message', (topic, message, packet) => {
    console.log(packet, message.toString())
})

验证效果

修改完成后,订阅端收到的Packet对象中会新增properties字段,包含你设置的userProperties:

Packet {
cmd: 'publish',
retain: false,
qos: 1,
dup: false,
length: xxx,
topic: 'test/connection708',
payload: <Buffer ...>,
properties: { userProperties: { user: 'property' } }
}

内容的提问来源于stack exchange,提问作者Hawkeyebrow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:42:57