Search code examples
javascripttypescriptmqttably-realtime

Need help using MQTT with Ably from the Browser


I am using the paho-mqtt library in a SPA running in Chrome and calling the connect with the example code and am getting two alternating errors

var client = mqtt.connect('mqtts:mqtt.ably.io', {
  keepalive: 30,
  username: 'keyPartA1.artA2',
  password: 'keyPartB',
  port: 8883
});

The errors repeat, not always in the same order...

stream.js?553e:64 WebSocket connection to 'ws://mqtt.ably.io:8883/' failed: Connection closed before receiving a handshake response
    WebSocketStream @ stream.js?553e:64
    createWebSocket @ ws.js?fcb9:59
    buildBuilderBrowser @ ws.js?fcb9:85
    wrapper @ index.js?e7fc:148
    MqttClient._setupStream @ client.js?df86:263
    MqttClient._reconnect @ client.js?df86:847
    eval @ client.js?df86:862
stream.js?553e:64 WebSocket connection to 'wss://mqtt.ably.io:8883/' failed: Connection closed before receiving a handshake response
    WebSocketStream @ stream.js?553e:64
    createWebSocket @ ws.js?fcb9:59
    buildBuilderBrowser @ ws.js?fcb9:85
    wrapper @ index.js?e7fc:148
    MqttClient._setupStream @ client.js?df86:263
    MqttClient._reconnect @ client.js?df86:847
    eval @ client.js?df86:862
stream.js?553e:64 WebSocket connection to 'ws://mqtt.ably.io:8883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
    WebSocketStream @ stream.js?553e:64
    createWebSocket @ ws.js?fcb9:59
    buildBuilderBrowser @ ws.js?fcb9:85
    wrapper @ index.js?e7fc:148
    MqttClient._setupStream @ client.js?df86:263
    MqttClient._reconnect @ client.js?df86:847
    eval @ client.js?df86:862

Solution

  • Firstly the URI should start with a proper schema, e.g. mqtts:// not just mqtts:

    Secondly, and the bit that is actually the cause of your problem, you can ONLY connect to a websocket or secure websocket enabled broker from within the browser. You CAN NOT connect to a native MQTTS broker from within a page. It looks like Ably's broker is expecting native MQTTS on port 8883, not MQTT over Websockets.