title: Setting up Paho Javascript Client (MQTT) with mosquitto on AWS EC2 Ubuntu + Ruby on Rails
body: <p>I have been trying to setup a MQTT broker on my AWS EC2 server, using the port 1883. So far it works with the <a href="https://github.com/njh/ruby-mqtt" rel="nofollow">ruby-mqtt gem</a>, but I am having trouble with setting it up with Paho Javascript Client for the website.</p>
  
  <p>What I have done so far:</p>
  
  <p><strong>Mosquitto</strong></p>
  
  <p>Installed mosquitto on my AWS EC2 instance, and it is running and listening on port 1883. I subscribed to a topic locally using the command</p>
  
  <pre><code>mosquitto_sub -h localhost -p 1883 -v -t 'topic1'
  </code></pre>
  
  <p><strong>AWS EC2 Security Group</strong></p>
  
  <p>Allow traffic over port 1883 (under tcp protocol)</p>
  
  <p><strong>Ruby on Rails</strong></p>
  
  <p>Installed ruby-mqtt gem, and tested the mqtt to be working by running the code below in rails console (development environment)</p>
  
  <pre><code>MQTT::Client.connect(ip_address_or_domain_name) do |c|
    c.publish('topic1', 'message to topic 1')
  end
  </code></pre>
  
  <p>The message appears in the terminal where <code>mosquitto_sub</code> was running.</p>
  
  <p><strong>Nginx</strong></p>
  
  <p>All this was done without any configuration on Nginx configuration files.</p>
  
  <p><strong>Paho Client</strong></p>
  
  <p>So I fired up a local rails server on my local computer, and run the example javascript snippet on one of my html view.</p>
  
  <pre><code>// Create a client instance
  client = new Paho.MQTT.Client("mqtt.hostname.com", Number(1883), "", "clientId")
  
  // set callback handlers
  client.onConnectionLost = onConnectionLost;
  client.onMessageArrived = onMessageArrived;
  
  // connect the client
  client.connect({onSuccess:onConnect});
  
  
  // called when the client connects
  function onConnect() {
    // Once a connection has been made, make a subscription and send a message.
    console.log("onConnect");
    client.subscribe("topic1");
    message = new Paho.MQTT.Message("Hello");
    message.destinationName = "topic1";
    client.send(message);
  }
  
  // called when the client loses its connection
  function onConnectionLost(responseObject) {
    if (responseObject.errorCode !== 0) {
      console.log("onConnectionLost:"+responseObject.errorMessage);
    }
  }
  
  // called when a message arrives
  function onMessageArrived(message) {
    console.log("onMessageArrived:"+message.payloadString);
  }
  </code></pre>
  
  <p>But I fail to connect. The error I am getting in the chrome developer console is:</p>
  
  <pre><code>WebSocket connection to 'ws://mqtt.example.com:1883/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
  </code></pre>
  
  <p>Im not sure what is wrong here. Greatly appreciate any help! Thanks in advance!</p>