Created
September 21, 2011 10:34
-
-
Save codeincontext/1231765 to your computer and use it in GitHub Desktop.
example of subscribing incoming websocket connections to redis using eventmachine
This file contains hidden or 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 'rubygems' | |
require 'eventmachine' | |
require 'em-websocket' | |
require 'json' | |
require 'em-hiredis' | |
EventMachine.run do | |
@channel = EM::Channel.new | |
@redis = EM::Hiredis.connect | |
puts 'subscribing to redis' | |
@redis.subscribe('ws') | |
@redis.on(:message) do |channel, message| | |
puts "redis -> #{channel}: #{message}" | |
@channel.push message | |
end | |
EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws| | |
puts 'Establishing websocket' | |
ws.onopen do | |
puts 'client connected' | |
sid = @channel.subscribe do |msg| | |
puts "#{msg} -> backbone" | |
ws.send msg | |
end | |
ws.onclose do | |
puts 'client disappeared' | |
@channel.unsubscribe(sid) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment