Mosca JS无法从服务器

时间:2016-05-21 15:52:26

标签: node.js express mqtt mosca

我正在尝试将Mosca MQTT服务器添加到我现有的Express应用程序中 我想向刚刚连接的客户端发送一条欢迎消息,但它无法正常工作。

const mqttServ = new mosca.Server({})
mqttServ.attachHttpServer(server)

var message = {
  topic: 'helloworld',
  payload: 'abcde', // or a Buffer
  qos: 0, // 0, 1, or 2
  retain: false // or true
}

mqttServ.on('clientConnected', (client) => {
  mqttServ.publish(message, client, () => {
    console.log('message sent')
  })
})

在网页上,我已将客户端命名为'/ hello / world'主题,但我没有得到任何内容。

var client = mqtt.connect()

client.subscribe('helloworld')

client.on('message', (topic, payload) => {
  console.log([topic, payload].join(": "))
  client.end()
})

- 更新 -
如果我在发布调用中删除了客户端,则消息会到达网页,但这不是我想要做的。

1 个答案:

答案 0 :(得分:0)

在订阅事件发布消息后发布消息

mqttServ.on('subscribed', (topic, client) => {
  mqttServ.publish(message, client)
})
相关问题