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 }
# Create the clients
im1 = "", "password"
im2 = "", "password"
# im1 creates a node
# im2 subscribe to that node
# We'll start a simple thread to get the events coming from that node to im2 { 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 *