CloudAMQP with MQTT and Ruby Getting started

Currently the most mature client library for Ruby is the synchronous ruby-mqtt. The async em-mqtt library need to support user/password before it's usable with CloudAMQP MQTT protocol.

First you need to add mqtt as a dependency to your Gemfile and execute bundle install

In the following code snippet you can see how to publish and subscribe from CloudAMQP MQTT. Note that the client is synchronous so you have to use threads if you want to subscribe and in the same time do other things.

CLOUDAMQP_MQTT_URL Structure mqtt://cloudamqp_username:cloudamqp_password@hostname:port

Code example Publish and subscribe

require 'mqtt'
require 'uri'

# Create a hash with the connection parameters from the URL
uri = URI.parse ENV['CLOUDAMQP_MQTT_URL'] || 'mqtt://localhost:1883'
conn_opts = {
  remote_port: uri.port,
  username: uri.user,
  password: uri.password,
} do
  MQTT::Client.connect(conn_opts) do |c|
    # The block will be called when you messages arrive to the topic
    c.get('test') do |topic, message|
      puts "#{topic}: #{message}"

MQTT::Client.connect(conn_opts) do |c|
  # publish a message to the topic 'test'
  loop do
    c.publish('test', 'Hello World')
    sleep 1

Full sample code can be found here. Worth noting is that the client does not yet support other QoS levels than 0, ie. no publish acknowledge or redelivery.