Skip to content

Connect FlowMQ with MQTT Ruby Client

FlowMQ's native support for MQTT makes it an excellent choice for Ruby applications that require real-time messaging. This guide will walk you through using the mqtt gem, a popular and straightforward client for MQTT, to connect to FlowMQ, publish messages, and subscribe to topics.

Prerequisites

Before you begin, ensure you have the following:

  • A running instance of FlowMQ.
  • Ruby 2.5 or later installed.
  • Bundler for managing gems.

Installation

Add the mqtt gem to your project's Gemfile and then install it using Bundler.

ruby
# Gemfile
source "https://rubygems.org"

gem "mqtt"

Then, run bundle install from your terminal:

bash
bundle install

Connecting to FlowMQ

To get started, you need to create a client instance and connect it to your FlowMQ broker.

ruby
require 'mqtt'

# Create a client instance
client = MQTT::Client.new('mqtt://localhost:1883', client_id: 'my-ruby-client')

# Connect to the broker
client.connect()
puts "Connected to FlowMQ!"

Publishing Messages

Once connected, you can easily publish messages to any topic using the publish method.

ruby
topic = 'flowmq/test/ruby'
payload = 'Hello FlowMQ from the Ruby client!'

client.publish(topic, payload)
puts "Published '#{payload}' to topic '#{topic}'"

Subscribing and Receiving Messages

To receive messages, you can use the get method, which subscribes to a topic and yields messages as they arrive. This method blocks, so it's best run in a separate thread for most applications.

ruby
# The `get` method will block and listen for messages.
# We'll run it in a thread to allow the main script to continue.
Thread.new do
  client.get do |topic, message|
    puts "Received message on topic '#{topic}': #{message}"
  end
end

Full Example

Here is a complete Ruby script that connects, subscribes, publishes a message, and then handles the incoming message.

ruby
require 'mqtt'

# Configuration
broker_address = 'localhost'
topic = 'flowmq/ruby/test'
client_id = 'ruby-example-client'

# Connect to the MQTT broker
puts "Connecting to #{broker_address}..."
MQTT::Client.connect(host: broker_address, client_id: client_id) do |client|
  puts "Connected!"

  # Subscribe to the topic in a separate thread
  Thread.new do
    client.get(topic) do |t, message|
      puts "Received message on #{t}: #{message}"
      # Disconnect after receiving one message for this simple example
      client.disconnect()
    end
  end

  # Allow a moment for the subscription to be established
  sleep(1)

  # Publish a message
  puts "Publishing message..."
  client.publish(topic, "A test message from mqtt-ruby.")
  
  # The get loop will keep the script alive until disconnected.
end

puts "Disconnected."

Additional Resources

  • For more advanced features, such as different QoS levels and retained messages, refer to the official mqtt-ruby repository.
  • Explore FlowMQ's advanced features for MQTT.