simplepubsub

The SimplePubSub gem uses a messaging system similar to MQTT.

Example

require 'simplepubsub'

# Subscribe example
SimplePubSub::Client.connect('a2.jamesrobertson.eu') do |client|
  client.get('test') do |topic, message|
    puts "#{topic}: #{message}"
  end 
end

# Publish example
SimplePubSub::Client.connect('a2.jamesrobertson.eu') do |client|
  client.publish('test', Time.now.to_s)
end

Requirement

s

To try an example similar to the one above you will need a web server which accepts publish and subscribe requests.

Here's examples of requests which are used with my web server (a2.jamesrobertson.eu):

Here's the Ruby Scripting file I used:

<package>
  <job id='reset'>
    <script>
    <![CDATA[

      @simplepubsub = {}
      'reset'

    ]]>
    </script>
  </job>   
  <job id='debug'>
    <script>
    <![CDATA[

      @simplepubsub.inspect

    ]]>
    </script>
  </job>     
  <job id='subscribe'>
    <script>
    <![CDATA[

      topic = params[:topic]
      uri = params[:uri]
      address = uri[/druby:\/\/([^:]+)/,1]
            
      @simplepubsub[topic] ||= {}
      @simplepubsub[topic].merge!({address => uri})
      
      'subscribed' + uri.inspect

    ]]>
    </script>
  </job>  
  <job id='publish'>
    <script>
    <![CDATA[ 

      require 'drb'    
      
      topic = params[:topic]

      if not @simplepubsub.include?(topic) and not @simplepubsub.include?('#') then
        return 'no topic subscribers' 
      end

      topic = URI.unescape(params[:topic])
      msg = URI.unescape(params[:msg] || params[:message])
      

      DRb.start_service

      topic_subscribers = @simplepubsub[topic]
      
      if topic_subscribers then
        topic_subscribers.values.each do |uri|
          next if @simplepubsub['#'].values.include? uri              
          echo = DRbObject.new nil, uri
          echo.message topic, @simplepubsub['#'].values.inspect + '__' + uri.inspect + msg
        end
      end
      
      any_topic_subscribers = @simplepubsub['#']
      
      if any_topic_subscribers then
        any_topic_subscribers.values.each do |uri|
          echo = DRbObject.new nil, uri
          echo.message topic, msg
        end
      end
      'published'
      
    ]]>
    </script>
  </job>
</package>

Resources

Tags:
Source:
2227hrs.txt
Published:
13-06-2013 22:27