Skip to content

Instantly share code, notes, and snippets.

@lporras
Forked from maccman/juggernaut_channels.rb
Created July 7, 2012 04:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lporras/3064583 to your computer and use it in GitHub Desktop.
Save lporras/3064583 to your computer and use it in GitHub Desktop.
Sinatra Server Side Event streaming with private channels.
# Usage: redis-cli publish message.achannel hello
require 'sinatra'
require 'redis'
conns = Hash.new {|h, k| h[k] = [] }
Thread.abort_on_exception = true
get '/' do
erb :index
end
get '/subscribe/:channel' do
content_type 'text/event-stream'
stream(:keep_open) do |out|
channel = params[:channel]
conns[channel] << out
out.callback do
conns[channel].delete(out)
end
end
end
Thread.new do
redis = Redis.connect
redis.psubscribe('message', 'message.*') do |on|
on.pmessage do |match, channel, message|
channel = channel.sub('message.', '')
conns[channel].each do |out|
out << "data: #{message}\n\n"
end
end
end
end
__END__
@@ index
<article id="log"></article>
<script>
var source = new EventSource('/subscribe/achannel');
source.addEventListener('message', function (event) {
log.innerText += '\n' + event.data;
}, false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment