Created
March 5, 2013 08:52
-
-
Save 7even/5088892 to your computer and use it in GitHub Desktop.
EM-based pubsub
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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