Skip to content

Instantly share code, notes, and snippets.

@technoweenie
Created June 17, 2011 14:38
Show Gist options
  • Save technoweenie/1031540 to your computer and use it in GitHub Desktop.
Save technoweenie/1031540 to your computer and use it in GitHub Desktop.
ZeroMQ pub/sub demo
# usage: ruby pub.rb CHAN USERNAME
#
# ruby pub.rb rubyonrails technoweenie
#
#
# binds a PUB socket to tcp://*:5555
require 'rubygems'
require 'zmq'
context = ZMQ::Context.new
chan = ARGV[0]
user = ARGV[1]
pub = context.socket ZMQ::PUB
pub.setsockopt ZMQ::IDENTITY, "#{chan}-#{user}"
pub.bind 'tcp://*:5555'
while msg = STDIN.gets
msg.strip!
pub.send "#{chan} #{user} #{msg}"
end
# usage: ruby sub.rb
#
# Connects a SUB socket to tcp://*:5555.
# Subscribes to rubyonrails and ruby-lang.
require 'rubygems'
require 'zmq'
context = ZMQ::Context.new
chans = %w(rubyonrails ruby-lang)
sub = context.socket ZMQ::SUB
if id = ARGV[0]
sub.setsockopt ZMQ::IDENTITY, id
puts "Identified as #{id}"
end
sub.connect 'tcp://127.0.0.1:5555'
chans.each { |ch| sub.setsockopt ZMQ::SUBSCRIBE, ch }
while line = sub.recv
chan, user, msg = line.split ' ', 3
puts "##{chan} [#{user}]: #{msg}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment