njh / ruby-mqtt

Pure Ruby gem that implements the MQTT protocol, a lightweight protocol for publish/subscribe messaging.
http://www.rubydoc.info/gems/mqtt
MIT License
542 stars 135 forks source link

Multiple clients #116

Closed FranciscoGJ closed 4 years ago

FranciscoGJ commented 6 years ago

I need to connect to two different brokers. How can I do it?

njh commented 6 years ago

Just create two different clients.

client1 = MQTT::Client.connect('test.mosquitto.org')
client2 = MQTT::Client.connect('iot.eclipse.org')
FranciscoGJ commented 6 years ago

Yes, I tried. But I can not get the two clients to listen. What would the code be like? Or is it necessary that each instance be found in different threads?

njh commented 6 years ago

Can you provide an example of what you are trying to do?

Are you subscribing in both clients?

FranciscoGJ commented 6 years ago

This is an example:

client1 = MQTT::Client.connect('test.mosquitto.org')
client2 = MQTT::Client.connect('iot.eclipse.org')

client1.get('backend/device/1') do |topic,message|
    @manage.check(topic,message)
end

client2.get('backend/ttn') do |topic,message|
    @manage.check(topic,message)
end
DemonGiggle commented 6 years ago

It looks like you are blocked by the first client.get

njh commented 4 years ago

That is right. The ruby MQTT::Client is synchronous. The #get blocks waiting for a message and calls the block for each message received.

If you want to wait for messages from two different brokers in the same process, then using threads might be an option.