Skip to content

Instantly share code, notes, and snippets.

@7even
Created March 5, 2013 08:52
Show Gist options
  • Save 7even/5088892 to your computer and use it in GitHub Desktop.
Save 7even/5088892 to your computer and use it in GitHub Desktop.
EM-based pubsub
require 'eventmachine'
require 'awesome_print'
class Channel
def initialize
@sockets = []
end
def subscribe(socket)
@sockets << socket
end
def publish(message)
@sockets.each { |socket| socket.send_data(message) }
end
def unsubscribe(socket)
@sockets.delete(socket)
end
end
$channel = Channel.new
module PubSub
def post_init
puts 'connection established'
$channel.subscribe(self)
end
def receive_data(data)
puts "received data: #{data.ai}"
$channel.publish(data)
end
def unbind
puts 'connection closed'
$channel.unsubscribe(self)
end
end
EM.run do
EM.start_server('0.0.0.0', 8081, PubSub)
Signal.trap('INT') { EM.stop }
Signal.trap('TERM') { EM.stop }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment