0

In my app.js:


  var mqtt = require('mqtt')
  var client  = mqtt.connect('mqtt://localhost:1883')
  topic = 'testTopic'

  client.on('connect', ()=> {
    client.subscribe(topic)
  })

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

I connected in hivemq-cli and hivemq server, then create a new topic testTopic in Test1 subscriptions, and let another subscribe to testTopic pic1

In hivemq-cli it's all ok, in my terminal:

testTopic3@localhost> sub -t testTopic -s
Hello
Hello
Hello
Hello
Hello
Hello
Hi
Hi
Hi

But when I use npm start, my web app said that: Firefox can't establish a connection to the server at ws://localhost:1883/, and return nothing.

I've been in this trouble for a day, so I'm very looking for some helps. Many thanks!

2 Answers2

1

You are using websockets (ws://) in your web app, which is probably a different port than MQTT port 1883 (mqtt://).

Gambit Support
  • 1,432
  • 1
  • 7
  • 17
  • So can you tell me how can I fix this? this is the first time I try with mqtt – Le Vu Minh Huy May 05 '20 at 13:09
  • First, learn about MQTT. Then try "mqtt://broker.hivemq.com" instead of "ws://localhost". – Gambit Support May 05 '20 at 13:24
  • Did you mean `var client = mqtt.connect('mqtt://broker.hivemq.com')` ? I also tried it, even `var client = mqtt.connect('mqtt://broker.hivemq.com:8000')` with http://www.hivemq.com/demos/websocket-client/. But nothing happens, browser still returns `can't establish a connection to the server at ws://broker.hivemq.com/` – Le Vu Minh Huy May 05 '20 at 13:36
  • The public HiveMQ broker enables WebSocket on path "/mqtt", so you need to change the url to broker.hivemq.com:8000/mqtt – SgtSilvio May 07 '20 at 07:08
1

You have to configure the listener in the HiveMQ configuration (conf/config.xml) and use the right port and path when connecting your client. The default configuration does not contain a WebSocket listener.

Example configuration:

<hivemq>
    <listeners>

        <!-- default configuration -->
        <tcp-listener>
            <port>1883</port>
            <bind-address>0.0.0.0</bind-address>
        </tcp-listener>

        <!-- WebSocket configuration -->
        <websocket-listener>
            <port>8000</port>
            <bind-address>0.0.0.0</bind-address>
            <path>/mqtt</path>
            <subprotocols>
                <subprotocol>mqttv3.1</subprotocol>
                <subprotocol>mqtt</subprotocol>
            </subprotocols>
            <allow-extensions>true</allow-extensions>
        </websocket-listener>
    </listeners>
<hivemq>

In this example you then need to connect your client to ws://localhost:8000/mqtt

More information for the configuration can be found in the documentation: https://www.hivemq.com/docs/hivemq/latest/user-guide/listeners.html#websockets

SgtSilvio
  • 476
  • 2
  • 5