我在 React 组件中使用 MQTT.JS。出于某种原因,当我尝试连接到我的 HiveMQ 主机时,连接函数会在 URL 前加上“localhost”
有人知道为什么会这样吗?
首先,我使用包含“主机”键的选项对象调用连接函数。结果是 connect 函数忽略了主机密钥并直接连接到 ws://localhost
const mqttConnect = (mqttOptions) => {
console.log(JSON.stringify(mqttOptions, null, 4))
setClient(mqtt.connect( mqttOptions ))
}
我尝试的第二件事是通过将其作为第一个参数来调用显式命名主机的函数。这导致连接函数在主机 URL 前面加上 ws://localhost
const mqttConnect = (mqttOptions) => {
console.log(JSON.stringify(mqttOptions, null, 4))
setClient(mqtt.connect( mqttOptions.host, mqttOptions) )
}
这是选项对象的样子:
mqtt选项:{ “主机”:“58xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx0c.s1.eu.hivemq.cloud”, “端口”:“8884”, "clientId": "icodefusion", "用户名": "icode", “密码”:“密码”, “协议”:“MQTT” }
我附上了错误的快照 https://imagizer.imageshack.com/img923/3495/UEAqem.jpg
protocol
键应该来自 URL.parse()
的输出所以应该包含 wss
而不是 MQTT
对于基于 websockets 的 MQTT。
我相信您没有阅读提到
protocolId
的文档
根据您显示的配置,这应该是调用
connect
函数的正确方法:
const mqttConnect = ({host, clientId, username, password}) => {
setClient(mqtt.connect(`wss://${host}`, {clientId, username, password}))
}
有关详细信息,请参阅https://www.npmjs.com/package/mqtt#api。