Skip to content

Mosquitto and JavaScript Example not working (Firefox)

I would like to make a Websocket connection with TLS encryption to my mosquitto server. But I do not even get a simple example with the official mosquitto server running.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Hello MQTT World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
    // Initialize a mqtt variable globally
    console.log(mqtt)


// connection option
const options = {
        clean: true, // retain session
      connectTimeout: 4000, // Timeout period
      // Authentication information
      clientId: 'test_client',
}

// Connect string, and specify the connection method by the protocol
// ws Unencrypted WebSocket connection
// wss Encrypted WebSocket connection
// mqtt Unencrypted TCP connection
// mqtts Encrypted TCP connection
// wxs WeChat applet connection
// alis Alipay applet connection
const connectUrl = 'wss://test.mosquitto.org:8081/mqtt'
const client = mqtt.connect(connectUrl,options)

client.on('reconnect', (error) => {
    console.log('reconnecting:', error)
})

client.on('error', (error) => {
    console.log('Connection failed:', error)
})

client.on('message', (topic, message) => {
  console.log('receive message:', topic, message.toString())
})
</script>
</head>
<body>
    <div id="logger"></div>
</body>
</html>

In the network Log I can see these statements:

...
[1]</</</v.prototype._setupReconnect
https://unpkg.com/mqtt/dist/mqtt.min.js:1:14126
[1]</</</v.prototype._cleanUp
https://unpkg.com/mqtt/dist/mqtt.min.js:1:15261
[1]</</</v.prototype._setupStream/this.connackTimer<
https://unpkg.com/mqtt/dist/mqtt.min.js:1:7007
(Async: setTimeout handler) [1]</</</v.prototype._setupStream
https://unpkg.com/mqtt/dist/mqtt.min.js:1:6920
[1]</</</v.prototype._reconnect
https://unpkg.com/mqtt/dist/mqtt.min.js:1:13732
[1]</</</v.prototype._setupReconnect/e.reconnectTimer<
https://unpkg.com/mqtt/dist/mqtt.min.js:1:14195
(Async: setInterval handler)
...

Firefox (Mozilla Firefox for Linux Mint 89.0 (64-bit)) gives the error message Firefox can’t establish a connection to the server at wss://test.mosquitto.org:8081/mqtt.

Maybe somebody can give me a hint what’s wrong with my setup? Or a know working JavaScript example?

Thanks in advance, Christof

Answer

First increase the connection timeout, you currently have it set to 4 seconds, the default is 30 seconds. Because test.mosquitto.org is a totally public broker it often gets hammered by people (either testing stuff or just not thinking what they are doing) so a longer timeout is better.

Secondly, having a clientID of test_client is VERY likely to clash with another client so your client will get kicked off the broker as soon as the other client tries to reconnect which will cause your client to reconnect causing a connect/disconnect loop. ClientID’s need to unique across ALL clients connecting to the broker, I suggest you change this to a unique to you prefix combined with a random number.

Thirdly you don’t actually do anything even if you connect, you make no subscriptions, so the on message event handler will never be called. You don’t even have a on connect event handler to know if you ever get connected cleanly.

e.g.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Hello MQTT World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
    // Initialize a mqtt variable globally
    console.log(mqtt)


// connection option
const options = {
        clean: true, // retain session
      connectTimeout: 30000, // Timeout period increased to 30 seconds
      // Authentication information
      clientId: 'foobar_test_random' + Math.floor(Math.random() * 10000),
}

// Connect string, and specify the connection method by the protocol
// ws Unencrypted WebSocket connection
// wss Encrypted WebSocket connection
// mqtt Unencrypted TCP connection
// mqtts Encrypted TCP connection
// wxs WeChat applet connection
// alis Alipay applet connection
const connectUrl = 'wss://test.mosquitto.org:8081'
const client = mqtt.connect(connectUrl,options)

//actually subscribe to something on a sucessfull connection
client.on('connect', (connack) => {
  client.subscribe('$SYS/#')
})

client.on('reconnect', (error) => {
    console.log('reconnecting:', error)
})

client.on('error', (error) => {
    console.log('Connection failed:', error)
})

client.on('message', (topic, message) => {
  console.log('receive message:', topic, message.toString())
})
</script>
</head>
<body>
    <div id="logger"></div>
</body>
</html>