Skip to content

Instantly share code, notes, and snippets.

@ryanbriones
Created April 22, 2011 01:12
Show Gist options
  • Save ryanbriones/935822 to your computer and use it in GitHub Desktop.
Save ryanbriones/935822 to your computer and use it in GitHub Desktop.
basic event machine pubsub for ChicagoRuby
#!/usr/bin/env ruby
require "rubygems"
require "eventmachine"
class PubSubServer < EM::Connection
attr_accessor :channels
SubscriberChannel = EM::Channel.new
def self.start(host = '0.0.0.0', port = 8080)
puts "starting PubSubServer"
EM.start_server(host, port, self)
end
def initialize
super
self.channels = []
end
def receive_data(data)
puts data.inspect
message = Message.new(data)
case message.command
when "SUBSCRIBE"
if channels.empty?
SubscriberChannel.subscribe do |pushed_message|
if channels.include?(pushed_message.channel)
send_data(pushed_message.message)
end
end
end
channels << message.channel
send_data("OK\n")
when "SEND"
SubscriberChannel.push(message)
send_data("OK\n")
else
send_data("I don't know what #{message.command} is\n")
end
end
end
class Message
attr_reader :command, :channel, :message
def initialize(data)
@data = data
parse_data
end
def parse_data
@command, @channel, @message = @data.strip.split(' ', 3)
end
end
EventMachine::run do
PubSubServer.start
end
#!/usr/bin/env ruby
require "rubygems"
require "eventmachine"
module Subscriber
def post_init
EM.defer do
ARGV.each do |channel|
puts "subscribing to #{channel}"
send_data("SUBSCRIBE #{channel}")
sleep 1
end
end
end
def receive_data(data)
puts data.inspect
end
end
EventMachine.run do
EventMachine.connect "0.0.0.0", 8080, Subscriber
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment