PubSub with XMPP4R-Simple

Posted by – 18/03/2009

As I already told you, I am using XMPP4R-Simple in an internal project. For this, I’d have to add PubSub capabilities to it, and I did when I decided to get serious with git. Today I committed a version with integration of various patches by other forks I found on GitHub plus a lot of improvements on PubSub functions.

With this version it’s simple to use PubSub like this:

require 'xmpp4r-simple'
 
# Simple function just to parse an event
require 'time'
def parse_event(event)
  item = event.children[0]
  node = item.node
  time = nil; item.each_element("//published") { |e| time = Time.parse(e.text) }
  text = nil; item.each_element("//body") { |e| text = e.text }
  return { :item => item, :node => node, :time => time, :text => text }
end
 
# Create the clients
im1 = Jabber::Simple.new "im1@example.com", "password"
im2 = Jabber::Simple.new "im2@example.com", "password"
 
# im1 creates a node
im1.create_node("/some/node")
 
# im2 subscribe to that node
im2.pubsubscribe_to("/some/node")
 
# We'll start a simple thread to get the events coming from that node to im2
Thread.new { loop {
  sleep 1 while ! im2.received_events?
  im2.received_events { |event|
    h = parse_event(event)
    puts ">>> Got an event from node #{h[:node]} published at #{h[:time]} with text #{h[:text]}"
  }
}}
 
# Now im1 just publishes anything to that node.
im1.publish_atom_item("/some/node", "This is my node", "This is the content of my node")
 
# The thread should capture the event and run puts on the hash from parsing.

PubSub is great, isn’t it?

Leave a Reply

Your email address will not be published. Required fields are marked *