Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Created September 21, 2011 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeincontext/1231765 to your computer and use it in GitHub Desktop.
Save codeincontext/1231765 to your computer and use it in GitHub Desktop.
example of subscribing incoming websocket connections to redis using eventmachine
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